1. β
Check if Element Exists
if ($('#myElement').length) {
console.log('Element exists!');
}
2. π Iterate Over Each Element
$('.items').each(function(index, element) {
console.log(index, $(element).text());
});
3. π Toggle Class
$('#btn').click(function() {
$('#box').toggleClass('active');
});
4. π― Smooth Scroll to Element
$('html, body').animate({
scrollTop: $('#target').offset().top
}, 500);
5. π±οΈ Click Outside to Close
$(document).mouseup(function(e) {
if (!$('#popup').is(e.target) && $('#popup').has(e.target).length === 0) {
$('#popup').hide();
}
});
6. π¦ Get Data Attribute
const value = $('#item').data('value');
7. β¨οΈ Trigger Function on Enter Key
$('#input').keypress(function(e) {
if (e.which === 13) {
alert('Enter pressed!');
}
});
8. π Change Element Text
$('#message').text('New message!');
9. π§ͺ Validate Input Not Empty
if ($.trim($('#name').val()) === '') {
alert('Name is required!');
}
10. β Debounce Input Event
let timeout;
$('#search').on('input', function() {
clearTimeout(timeout);
timeout = setTimeout(() => {
console.log('Search:', this.value);
}, 300);
});
11. π Append Element
$('#list').append('<li>New Item</li>');
12. π§Ή Empty Element
$('#content').empty();
13. ποΈ Remove Element
$('.ad-banner').remove();
14. π¨ Change CSS Dynamically
$('#box').css({
backgroundColor: 'blue',
fontSize: '18px'
});
15. π Get Element Height
const height = $('#header').outerHeight();
16. π Prevent Default Form Submit
$('form').submit(function(e) {
e.preventDefault();
alert('Form prevented!');
});
17. πΈ Fade In Element
$('#modal').fadeIn(300);
18. π» Fade Out Element
$('#overlay').fadeOut(300);
19. π Slide Toggle
$('#toggle-btn').click(function() {
$('#panel').slideToggle();
});
20. π§ Get Selected Option Text
const selected = $('#dropdown option:selected').text();
21. π― Set Input Value
$('#email').val('user@example.com');
22. π Disable a Button
$('#submitBtn').prop('disabled', true);
23. π Enable a Button
$('#submitBtn').prop('disabled', false);
24. π² Randomize Array Elements
function shuffleArray(arr) {
return arr.sort(() => 0.5 - Math.random());
}
25. π Clone Element
const clone = $('#template').clone().appendTo('#container');
26. π Find Child Element
const child = $('#parent').find('.child-class');
27. β Delay an Action
$('#box').fadeOut(0).delay(500).fadeIn(300);
28. π Loop Through JSON Data
const data = [{ name: 'Alice' }, { name: 'Bob' }];
$.each(data, function(i, item) {
console.log(item.name);
});
29. π Load HTML via AJAX
$('#container').load('/content.html');
30. π Send AJAX POST Request
$.post('/submit', { name: 'Parth' }, function(response) {
console.log('Success:', response);
});
Top comments (0)