Category - jQuery

Mastering jQuery: Simple Tricks for Success
Aug 10, 2020

1. Back to top button $('a.top').click(function() { $(document.body).animate({scrollTop : 0},800); return false; }); //Create an anchor tag <a class=”top” href=”#”>Back to top</a> As you can see using the animate and scrollTop functions in jQuery we don’t need a plugin to create a simple scroll to top animation. By changing the scrollTop value we can change where we want the scrollbar to land, in my case I used a value of 0 because I want it to go to the very top of our page, but if I wanted an offset of 100px I could just type 100px in the function. So all we are really doing is animating the body of our document throughout the course of 800ms until it scrolls all the way to the top of the document. 2. Checking if images are loaded $(‘img’).load(function() { console.log(‘image load successful’); }); Sometimes you need to check if your images are fully loaded in order to continue with your scripts, this three line jQuery snippet can do that for you easily. You can also check if one particular image has loaded by replacing the img tag with an ID or class.   3. Fix broken images automatically $('img').error(function(){ $(this).attr('src', ‘img/broken.png’); }); Occasionally we have times when we have broken image links on our website and replacing them one by one isn’t easy, so adding this simple piece of code can save you a lot of headaches. Even if you don’t have any broken links adding this doesn’t do any harm.   4. Toggle class on hover $(‘.btn').hover(function(){ $(this).addClass(‘hover’); }, function(){ $(this).removeClass(‘hover’); }); We usually want to change the visual of a clickable element on our page when the user hovers over and this jQuery snippet does just that, it adds a class to your element when the user is hovering and when the user stops it removes the class, so all you need to do is add the necessary styles in your CSS file.   5. Disabling input fields $('input[type="submit"]').attr("disabled", true); On occasion you may want the submit button of a form or even one of its text inputs to be disabled until the user has performed a certain action (checking the “I’ve read the terms” checkbox for example) and this line of code accomplishes that; it adds the disabled attribute to your input so you can enable it when you want to. To do that all you need to do is run the removeAttr function on the input with disabled as the parameter: $('input[type="submit"]').removeAttr("disabled”);   6. Stop the loading of links $(‘a.no-link').click(function(e){ e.preventDefault(); }); Sometimes we don’t want links to go to a certain page or even reload it, we want them to do something else like trigger some other script and in that case this piece of code will do the trick of preventing the default action.   7. Toggle fade/slide // Fade $( “.btn" ).click(function() { $( “.element" ).fadeToggle("slow"); }); // Toggle $( “.btn" ).click(function() { $( “.element" ).slideToggle("slow"); }); Slides and Fades are something we use plenty in our animations using jQuery, sometimes we just want to show an element when we click something and for that the fadeIn and slideDown methods are perfect, but if we want that element to appear on the first click and then disappear on the second this piece of code will work just fine.   8. Make two divs the same height $(‘.div').css('min-height', $(‘.main-div').height());   9. Self-closing elements When inserting empty elements into the DOM, you can use self-closing tags: $('#el1').append('<table class="holly" />'); $('#el2').before('<p class="user-message note" />');   10. Inserting content —Before, after, prepend or append? When inserting elements into an element, use .prepend() or .append(). The difference is that prepend inserts the new element into the start (i.e. insert element as the first child), while append does the exact opposite, inserting the element as the last child: $('div').prepend('<p>Hello!</p>').append('<p>Goodbye!</p>');   11. Loopy doopy do! Very often people wonder how to loop through each element individually, and then target the current element. For this purpose, we can use .each() and $(this). Let’s say we want to add a class to all paragraphs, based on their index. If you are working on a static page, you might be tempted to hardcode it: $('p').each(function (i) {     $(this).addClass('para-' + (i+1)); } Remember that i is a zero-based index, i.e. it starts from 0 for the first encountered element.   12. Automatic vendor prefixes jQuery automatically adds vendor prefixes when it sees fit — therefore saving you the headache of adding vendor prefixes yourself: $('.box').css({ 'transform': 'translate(100,100) scale(2)' }); 13. Selectors As previously mentioned, one of the core concepts of jQuery is to select elements and perform an action. jQuery has done a great job of making the task of selecting an element, or elements, extremely easy by mimicking that of CSS. On top of the general CSS selectors, jQuery has support for all of the unique CSS3 selectors, which work regardless of which browser is being used. $('.feature');           // Class selector $('li strong');          // Descendant selector $('em, i');              // Multiple selector $('a[target="_blank"]'); // Attribute selector $('p:nth-child(2)');     // Pseudo-class selector 14. 'this' Selection Keyword When working inside of a jQuery function you may want to select the element in which was referenced inside of the original selector. In this event the this keyword may be used to refer to the element selected in the current handler. $('div').click(function(event){    $(this); });   15. jQuery Selection Filters Should CSS selectors not be enough there are also custom filters built into jQuery to help out. These filters are an extension to CSS3 and provide more control over selecting an element or its relatives. $('div:has(strong)');   16. Slide Demo //HTML <div class="panel">   <div class="panel-stage"></div>   <a href="#" class="panel-tab">Open <span>&#9660;</span></a> </div>   //Function $('.panel-tab').on('click', function(event){   event.preventDefault();   $('.panel-stage').slideToggle('slow', function(event){     if($(this).is(':visible')){       $('.panel-tab').html('Close <span>&#9650;</span>');     } else {       $('.panel-tab').html('Open <span>&#9660;</span>');     }   }); });   17. Tabs Demo //HTML <ul class="tabs-nav">   <li><a href="#tab-1">Features</a></li>   <li><a href="#tab-2">Details</a></li> </ul> <div class="tabs-stage">   <div id="tab-1">...</div>   <div id="tab-2">...</div> </div> // Show the first tab by default $('.tabs-stage div').hide(); $('.tabs-stage div:first').show(); $('.tabs-nav li:first').addClass('tab-active'); // Change tab class and display content $('.tabs-nav a').on('click', function(event){   event.preventDefault();   $('.tabs-nav li').removeClass('tab-active');   $(this).parent().addClass('tab-active');   $('.tabs-stage div').hide();   $($(this).attr('href')).show(); });   RELATED BLOGS: New Features and Highlights of Bootstrap 5

magnusminds website loader