Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The jquery code works on console but not in script tags or in attached js file

Tags:

jquery

click

$(".filter-close").click(function(){
    $(this).parent().remove();

});

this snippet works in console but neither in script tags nor in attached js file.

like image 984
Srujan Thadagoppula Avatar asked Jul 28 '15 08:07

Srujan Thadagoppula


1 Answers

Wait for the DOM to be ready when calling your event handler:

jQuery(function($) { // this does the trick and also makes sure jQuery is not conflicting with another library 
    $(".filter-close").click(function(){
        $(this).parent().remove();
    });
});

When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code

Documentation for .ready() method

like image 99
D4V1D Avatar answered Oct 20 '22 19:10

D4V1D