Some Useful JavaScript & jQuery Snippets – Part 2

Check if cookies are enabled $(document).ready(function() { var dt = new Date(); dt.setSeconds(dt.getSeconds() + 60); document.cookie = “cookietest=1; expires=” + dt.toGMTString(); var cookiesEnabled = document.cookie.indexOf(“cookietest=”) != -1; if(!cookiesEnabled){ //cookies are […]

  • Check if cookies are enabled
  • $(document).ready(function() {
        var dt = new Date();
        dt.setSeconds(dt.getSeconds() + 60);
        document.cookie = "cookietest=1; expires=" + dt.toGMTString();
        var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
        if(!cookiesEnabled){
            //cookies are not enabled
        }
    });
  • Toggle all checkboxes
  • var tog = false; // or true if they are checked on load
    $('a').click(function() {
        $("input[type=checkbox]").attr("checked",!tog);
        tog = !tog;
    });
  • Get the index of an element
  • $("ul > li").click(function () {
        var index = $(this).prevAll().length;
    });
  • Validate date of birth
  • $("#lda-form").submit(function(){
        var day = $("#day").val();
        var month = $("#month").val();
        var year = $("#year").val();
        var age = 18;
        var mydate = new Date();
        mydate.setFullYear(year, month-1, day);
    
        var currdate = new Date();
        currdate.setFullYear(currdate.getFullYear() - age);
        if ((currdate - mydate) < 0){
            alert("Sorry, only persons over the age of " + age + " may enter this site");
            return false;
        }
        return true;
    });

    Tiny break: 📬 Want to stay up to date with frontend and trends in web design? Subscribe and get our Collective newsletter twice a tweek.

  • Test if an element is visible
  • if($(element).is(":visible")) {
        //The element is Visible
    }
  • Counting child elements
  • <div id="foo">
    <div id="bar"></div>
    <div id="baz">
    <div id="biz">
    </div>
    <span><span>
    </div>
    
    //jQuery code to count child elements
    $("#foo > div").length
  • Center an element on the screen
  • jQuery.fn.center = function () {
        this.css("position","absolute");
        this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
        this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
        return this;
    }
    
    //Use the above function as:
    $(element).center();
  • Moving options from list A to list B
  • $().ready(function() {
        $('#add').click(function() {
            !$('#select1 option:selected').appendTo('#select2');
        });
        $('#remove').click(function() {
            !$('#select2 option:selected').appendTo('#select1');
        });
    });
  • Select all checkboxes
  • $(document).ready(function(){
        $("#checkboxall").change(function(){
            var checked_status = this.checked;
            $("input[name=checkall]").attr("checked", checked_status);
        });
    
    });
  • Get the current URL
  • $(document).ready(function() {
        var pathname = window.location.pathname;
    });
  • Check if and which key was pressed
  • $(function() {
        $(document).keypress(function(e){
            switch(e.which){
            // "ENTER"
            case 13:
            alert('enter pressed');
            break;
    
            // "s"
            case 115:
            alert('s pressed');
            break;
    
            (...)
    
            }
        });
    
    });

    Message from TestkingWe are among the best ccie service provider to help you better prepare for ccna exam. Sign up for online prep course to successfully pass ccie wireless certification.

    cody

    Cody loves jQuery - he puts the magic into every web application. He is crazy about Curry dishes.

    Stay in the loop: Get your dose of frontend twice a week

    👾 Hey! Looking for the latest in frontend? Twice a week, we'll deliver the freshest frontend news, website inspo, cool code demos, videos and UI animations right to your inbox.

    Zero fluff, all quality, to make your Mondays and Thursdays more creative!

    Feedback 28

    Comments are closed.
    1. Pingback: Some Useful JavaScript & jQuery Snippets | Codrops

    2. Pingback: Some Useful JavaScript & jQuery Snippets – Part 2 | Codrops « Netcrema – creme de la social news via digg + delicious + stumpleupon + reddit

    3. Pingback: Some Useful JavaScript & jQuery Snippets – Part 2 | Codrops : Popular Links : eConsultant

    4. As far as I know – some of those can be optimized (use .length instead of size(), referencing variables when used twice, etc). Otherwise – nice scripts indeed. Just a sidenote – with the upcoming 1.4 jQuery (due 14th of January) getting the index will be easier: $(“ul > li”).index();

      Kindest regards,
      Ivan

    5. sigh…

      To select checkboxes, use the :checkbox pseudoselector instead of the type attr. To toggle checkboxes, you need to use attr(“checked”,”checked”) and removeAttr(“checked”);

      .is() returns a boolean. You can just do if ($(foo).is(“:checked”)). Comparison at all is unnecessary, much less comparing it to the string “true.”

      There is no reason for the return statement in the moving select options example.

      The correct event to use for checkboxes is the change event, not the click event, as shown in the select all checkboxes example. Also, to check all the checkboxes, use $(“input[name=checkall]”).attr(“checked”,”checked”); The @ in attribute selectors was deprecated in jQuery 1.3, and there is no need for an .each() in that circumstance.

      Also, as Ivan mentions above, .length instead of .size() and storing references to queries should be included in these snippets.

      These may seem like nitpicks but when posts like this include wrong information or practises they are passed along and duplicated by more and more people.

    6. Pingback: Some Useful JavaScript & jQuery Snippets - Part 2 | Codrops Blog

    7. Cody, thanks for the updates, It’s great to make sure the snippets that get distributed follow best practices. 🙂

      You still got a
      if($(element).is(“:visible”) == “true”) {
      which would be fine to leave as:
      if($(element).is(“:visible”)) {

      cheers.

    8. Pingback: Some Useful JavaScript & jQuery Snippets - Part 3 | Codrops

    9. if($(element).is(“:visible”)) {
      this doesn’t take visibility of element’s parents into account. something like this might lead to the expected behaviour:
      if($(element).is(“:visible”) && $(element).parents().not(‘:visible’).length == 0) {…

    10. Pingback: Snippets de Javascript y jQuery para ahorrar tiempo (Parte 2) - elWebmaster.com

    11. Pingback: links for 2010-01-17 « Web????????? Web??????????? S5-Style

    12. Nice snippet for the element index, I always used a each() for that.that have working capability

      Thanks. 🙂

    13. Nice to extract the index of the item, I always used one each () to do so. Thank you. 🙂

    14. Just a sidenote – with the upcoming 1.4 jQuery (due 14th of January) getting the index will be easier: $(“ul > li”).index();

    15. if($(element).is(“:visible”)) {
      this doesn’t take visibility of element’s parents into account. something like this might lead to the expected behaviour:
      if($(element).is(“:visible”) && $(element).parents().not(‘:visible’).length == 0) {…

    16. Cody great share. this will work perfectly with a few projects I’m working on