Simply we handle the resize event of the window. We can thus adjust the size or appearance of the elements depending on the window size. $(window).resize(myHandler); function myHandler() { alert(‘Do something …’); }
All posts by jQuery
Number of matching elements found
This simple trick gives us information of how many elements of the document matches the selector (e.g. find by the CSS class) alert($(“.our-class-css”).size());
Checking if a checkbox is checked
It’s simple – can be done in such a way: if ($(“#myCheckBoxID”).is(‘:checked’)) { … }; or by checking an attribute: if ($(‘#myCheckBoxID’).attr(‘checked’)) { … };
Run JavaScript Only After Entire Page Has Loaded
This is when the whole page has finished loading. For example, this will wait for images to be finished loading, so that you can measure their widths and heights accurately. $(window).bind(“load”, function() { // code here });
Smarter Event Binding
$(“p”).on(“click”, function(){ $(this).css(“color”, “red”); }); The reason this is smarter is because there are likely many p elements on the page. If there were, say, 10 of them, traditional click event binding would require 10 handlers. The live function only requires one, reducing memory needed by the browser. Then imagine compounding the issue by 100 […]
Check if jQuery is Loaded
if (typeof jQuery == ‘undefined’) { // jQuery IS NOT loaded, do stuff here. } css tricks
Add Active Navigation Class Based on URL
Ideally you output this class from the server side, but if you can’t… Let’s say you have navigation like this: <nav> <ul> <li><a href=”/”>Home</a></li> <li><a href=”/about/”>About</a></li> <li><a href=”/clients/”>Clients</a></li> <li><a href=”/contact/”>Contact Us</a></li> </ul> </nav> And you are at the URL: http://yoursite.com/about/team/ And you want the About link to get a class of “active” so you can […]
Redirect webpage in JavaScript
This javascript code should perform http redirect on a given URL. window.location.href = http://viralpatel.net”;
Smooth(animated) page scroll
$(document).ready(function() { $(‘a[href*=#]’).click(function() { if (location.pathname.replace(/^//,”) == this.pathname.replace(/^//,”) && location.hostname == this.hostname) { var $target = $(this.hash); $target = $target.length && $target || $(‘[name=’ + this.hash.slice(1) +‘]’); if ($target.length) { var targetOffset = $target.offset().top; $(‘html,body’) .animate({scrollTop: targetOffset}, 900); return false; } } }); // how to use // place this […]
HTML5 Data Attributes
HTML5 data attributes are a simple means to embed data in a webpage. It is useful for exchanging data between the server and the front end, something that used to require outputting <script> blocks or hidden markup. With the recent updates to the jQuery data() method, HTML5 data attributes are pulled automatically and are available […]