jQuery Snippets

Here are list of JQuery code snippets updated ongoing bases

0. Attach Custom Function to HTML Element
(function ($) {
    $('.image_button').click(function(e){
        e.preventDefault();
        var img_src = $(this).find('img').attr('src');
        $('#focus-image').attr('src',img_src);
    });
})(jQuery);

Here, we put everything in parentheses so it executes on page load while passing jQuery object and assign it to “$” symbol. Afterwards, search the html element with class ‘image_button’ and assign click event with our function. This function grabs src from one element and swaps with another

1. How to find events attached to particular element
$._data($('a[href="/node/56/edit"]')[0], "events");

the first element in the _date() function is the element. In our case, that is a link with an attribute of ‘href’ equal to specific path

or with chrome Developer tools select “inspect element’ on the element and then look at the righ

2. How to assign your custom methods to an DOM element
(function(window, document, $) {

var prototype = $.fn,
	    placeholder;
...
            placeholder = prototype.placeholder = function() {
			return this;
		};
            function customFunciton() {
                    //do something
            }
}(this, document, jQuery));

Here, the prototype refers the global prototype heap, so by assigning function placeholder() to the global prototype we make it available to call on any of the element we wish:

$('textarea').placeholder();

So this will assign the scope with all our custom function, so anyone can all the custom function ‘customFunction’ from now on

3. Ways to call your Custom function
$(window).on('load', function () {
    $('[data-ride="carousel"]').each(function () {
      var $carousel = $(this)
      $carousel.carousel($carousel.data())
    })
  })

Here, onload event we search for dom element and then once found execute our costum method ‘carousel’

4. Stop Event

Once you attach an event to an element(i.e.btn-nav-toggle-responsive) to the link tag, you may want it not to go anywhere. In that case, you prevent the default behaviour

$('.btn-nav-toggle-responsive').click(function(e){
		$('.left-sidebar').toggleClass('show-fullsidebar');
        e.preventDefault();
	});

Here, we passing in the event ‘e’, so that we can call ‘preventDefault() that prevents from going to a different link

5. Trigger Event From Console

To trigger events from console:

var my_e = jQuery.Event("some_event_id");
jQuery("body").trigger(my_e)

This will trigger event ‘some_event_id’ from console
To trigger event from code:

$.event.trigger({
            type: "reset_image_ds"
        });
6. Load JS Library from Console

There are at least two ways:

jQuery.getScript('http://dev-ckeditor/ckeditor/ckeditor.js');

In this approach we use jQuery libarary to load script ckeditor.js. An altertnative, is:

var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'script.js';
document.head.appendChild(script);

For stylesheets:

document.appendStyleSheet('/path/bootstrap.min.css');
7. Decode String in jQuery

Perhaps, you garbed html text just to learn it is in the encoded form. To decode it back into html tags:

var decodedHtml = jQuery('<textarea/>').html("SOME-STRING-WITH-HTML-CHARACTERS").val();

This will take all html character symbols and convert to appropriate tags names

8. jQuerify HTML

Perhaps, you have raw HTML and you would like to make into jQuery elements, so you can take advantage of jQuery Lib:

var b = jQuery(decodedOldHtml);
var output = b.find('.wrapper-end').html();

This will take each html element and wrap into jQuery objects. Afterwards, you can call jQuery Api as we did here to find certain element(i.e. wrapper-end)

Note: You will get error –

“Uncaught Error: Syntax error, unrecognized expression:”

if the content you are trying to jQuerify(i.e. decodeOldHtml) is not wrapped into any tags. The good practice always wrap into some tags before jQuerify as following:

jQuery('<div>' + decodedOldHtml + '</div>');

This way you will avoid the Syntax error all times for text only content. The more important it will not break on ‘find’ calls by putting it all in one jQuery object. For more, see jquerify-string-to-find-element-fails. At last, ensure the wrapping tags are not ‘body’ because jQuery ignores the ‘body’ tag wrapper

9. Make jQuery Sandbox

It may be too long of name – jQuery to type each time, so what often is done is create jQuery sandbox and pass the “$” as jQuery object:

(function ($) {
       console.log($('find-me').html());
})(jQuery);

Here,we first wrap our code into parentheses, so besides parsing it is also executed. In addition,for our code block, we pass in jQuery object by putting at the end and assigning it to “$” since its the parameter in the function.

Often times your code will do some manipulation on DOM, then you probably like to make sure DOM is loaded before the code in your sandbox is executed:

jQuery(document).ready(function($) {
       console.log($('find-me').html());
});

So, we attach event ‘ready’ before executing the sandbox

At last, it may be the case you will merge your code with other javascript files, then add ‘;’ in front to avoid breaking the execution:

;jQuery(document).ready(function($) {
       console.log($('find-me').html());
})(jQuery);
9. Remove and Replace DOM Elements

Some of the most common manipulations to the DOM is remove & replace. To remove element with its children:

$('.find-me').empty();

This will remove the element ‘.find-me’ and all of the children(the tree) below
To replace an element or often times remove the element but not the children:

var cnt = $('.find-me').contents();
 $('find-me').replaceWith(cnt);

This will take out the element ‘.find-me’ but keep all the children intact.

JS Widget Boilerplate

There are probably several ways to setup and organize code for your JS widget. Here is one I find common and works well for me:

if (!window.VIRTUAL_HOSTY) {
    /**
     * @singleton
     */
    window.VIRTUAL_HOSTY = (function ($) {

        //private variables come here...
        var base_url = window.BASE_URL || '/',
            log_on = false;

        //private function to initiate your widget
        var _init = function () {
            $(window.document).ready(function ($) {
               _parse_url();
            });
        }

        //public interface...the API for your widget
        return {
            set_base: function (some_val) {//function to set private variable
                base_url = some_val;
            },
            get_base: function () {//function to retrieve private variable
                return base_url;
            },
            init: function(){//public function called to initialize widget
              _init();  
            },
            turnOnDebug: function () {//public function to turn on logging
                log_on = true;
            }
        }
    })(jQuery);
}

Here we create global variable VIRTUAL_HOSTY that is the access point of our Widget. All the interaction happens via this variable. The VIRTUAL_HOSTY returns an object. All of the functions specified in this object is public. Everything else is private since we wrapped it into parentheses “()” making the scope execute at the time of load accessible only with the references in the returned object VIRTUAL_HOSTY

Once you have the widget lib file imported you can call on it:

<script>
VIRTUAL_HOSTY.turnOnDebug();
VIRTUAL_HOSTY.init();
</script>

Here,we turn on logging and then initiate our widget VIRTUAL_HOSTY

Leave a Reply

Your email address will not be published. Required fields are marked *