10 Jquery Snippets Every Developer Should Know 

by admin Date: 13-02-2014 jquery resources tutorials tips plugins snippets webdev


For this post, we would like to share with our readers 10 JQuery Code Snippets which we’ve collected that users can copy and paste directly into their themes by which to create some nice visual effects which will spruce up your website. Enjoy !

1. Smooth Scrolling for Internal Links

$('a[href^="#"]').bind('click.smoothscroll',function (e) { 
 e.preventDefault(); 
   var anchor = this.hash,  
$target = $(target); 
   $('html, body').stop().animate({ 
 'scrollTop': $target.offset().top 
 }, 500, 'swing', function () {
  window.location.hash = anchor; 
 }); 
   });  

2. JS : jQuery Get All Nodes, Including Orphaned Text

var $element = $('#my-element'); 
var $nodes = $element.contents(); 
$nodes.each(function() {
if(this.nodeType === 3 && $.trim($(this).text())) { 
$(this).wrap('');
}
}); 

3. Select Box Restrict

$("#categories option").click(function(e){
  if ($(this).parent().val().length > 2) {
  $(this).removeAttr("selected"); 
 }  
});

4. Facebook Get User Permissions and Send These Via Ajax

// always put this function inside a click or a user action, don't automatically open it or browser will block the popup.  
$('#button_id').click(function(){  
FB.login(function(logged) {  
if(logged.status == "connected"){  
FB.api("/me", function(response) {
  $.ajax({  type: "POST",  url: "pass_value.php",  data: {
fb_id: response.id, name: response.first_name, last_name: response.last_name,
 gender: response.gender},  success: 
function(){window.location.href = "gosomewhere.php"; 
} 
 });  
});  
}  /* in the scope u specify all permission you need, in this case you get all basic INFO and pubblish to wall permission */
  }, {scope: 'publish_stream'}); 
   });

5. jQuery Remove Class with WildCard

var _c = 'your-icon-class'
$('.currency').removeClass (function (index, css) {
return (css.match (/\bicon-\S+/g) || []).join(' ');
}).addClass('icon-'+_c);

6. jQuery Toggle Disabled

/* HTML 
|
|
|
 <input type="text"value="I &lt;3 EMOTICODE <img src="http://codegeekz.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley"> " />  <input type="button" value="Toggle Disabled" />
| 
|
|
*/ 
// Plugin 
(function($) { 
$.fn.toggleDisabled = function() { 
return this.each(function() { 
var $this = $(this); 
if ($this.attr('disabled')) $this.removeAttr('disabled'); 
else $this.attr('disabled', 'disabled'); 
 }); 
};  })(jQuery); 
 // TEST 
$(function() { 
  $('input:button').click(function(){ 
  $('input:text').toggleDisabled();   
});   
});

7. Smooth Scroller

// HTML:  //
  <h1 id="anchor">Lorem Ipsum</h1>
//<a class="topLink" href="#anchor">Back to Top</a>
$(document).ready(function()
{    $("a.topLink").click(function() {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top + "px"
},
{  duration: 500,  easing: "swing"
});  return false;
});
});

8. Form Tracking with JS and Google Analytics

var array1 = [];
$(document).ready(function () {
$('input').change(function () {
var formbox = $(this).attr('id');  array1.push(formbox);
  console.log("you filled out box " + array1);
});
$('#submit').click(function ()
{  console.log('tracked ' + array1);
 //alert('this is the order of boxes you filled out: ' + array1);
 _gaq.push(['_trackEvent', 'Form', 'completed', '"' + array1 + '"']);
});
  }); 

9. Test Password Strength

$('#pass').keyup(function(e){
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
if (false == enoughRegex.test($(this).val())) {
$('#passstrength').html('More Characters');  }
else if (strongRegex.test($(this).val())) {
$('#passstrength').className = 'ok';
  $('#passstrength').html('Strong!');  }
else if (mediumRegex.test($(this).val())) {
$('#passstrength').className = 'alert';
$('#passstrength').html('Medium!');  }
else {
$('#passstrength').className = 'error'; 
$('#passstrength').html('Weak!');
}
return true;
});

10. Make Entire Div Clickable

<div class="myBox">blah blah blah.
<a href="http://google.com">link</a></div>
[/jquery]
The following lines of jQuery will make the entire div clickable:
[jquery]
$(".myBox").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});

 

 

 

 

 
by admin Date: 13-02-2014 jquery resources tutorials tips plugins snippets webdev hits : 10578  
 
 
 
 

Related Posts

    Best Open-Source Javascript Date Picker Plugins and Libraries

    For date pickers, selecting menus is a common choice as they are simple to set up. But I suppose our customers deserve better after centuries of using MM / DD…

    Understanding the JavaScript language (guidelines for beginners)

    What began in 1995 as a modest 10-day project is now one of the world's most commonly used programming languages. JavaScript is actually everywhere, thanks to more advanced JavaScript engines…

    How To Grow Your Small Business

    A business that stays still will stagnate. To be successful and to have a business to be proud of, you need to ensure that it grows. This is not always…

    Level Up Your JavaScript Skills: 12 basic notions

    If you are a developer at any level, understanding its basic concepts is crucial. This article highlights 12 basic concepts that are critical to understanding by any JS developer, but do…

    Is jQuery going to die in 2019?

    For a while, JQuery's relevance has been a topic of debate among web developers. We were curious as web developers interested in Javascript to know what others have to say…

    Best 5 Javascript NewsTicker Plugins

    Not all developers know the marquee tag of HTML, that allows you to create a scrolling piece of text or image displayed that is shown horizontally or vertically on the DOM.…

    Best Javascript front-end hacking cheatsheets

    JavaScript has a extremely high potential to build cutting-edge web applications. But it's really hard to memorize it by heart. The JavaScript cheat sheets therefore act perfectly as a reminder…

    Tips for JavaScript Developers in 2019

    Another year is over and JavaScript is constantly changing. However, there are some tips that can help you write in 2019 clean and efficient code that scales. Below is a…

    Working with JSON in JavaScript

    JSON is short for JavaScript Object Notation and an easy - to - access way to store information. In short, it gives us a collection of human - readable data…

    JavaScript Basis: Syntax & Structure

    Programming languages are defined by rules. The syntax is what we follow when we write our code, which forms the logical structure of our programs. Let's dive right into the basic…

    Crazy SEO Tips For 2019

    Are you interested in learning more about SEO in 2019? Here are the trends you need to follow to improve your search optimization skills. For those who don’t know about SEO,…

    Top 10 JavaScript Books 2019

    Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications. If you're an aspiring web developer then…