Issue with jQuery .on() function on DOM created elements - javascript

In my web application I use .on() from jQuery to bind click event to a specific li elements in a dynamic multilevel menu created by an AJAX call and passed to the DOM.
$(".dl-menu li:not(:has(li)):not(.dl-back)").on("click", function(){
// My Code...
});
Obviously I put this code behind all the dependencies (jQuery in this case), but I does not work, the code is not being executed.
Only works if I open Firebug and paste the code in it.
I also have tried this:
$(document).ready(function() {
$(".dl-menu li:not(:has(li)):not(.dl-back)").on("click", function(){
// My Code...
});
});
But it does not work too.
What I'm doing wrong?
EDIT: To add more details:
HTML structure:
<div id='tab2' class='col s12'>
<div class='section no-pad-bot' id='index-banner'>
<br><br>
<h2 class='header center green-text'>MENU</h2>
<div id='prodcontainer'>
<div id='dl-menu' class='dl-menuwrapper'></div>
</div>
</div>
</div>
AJAX: (the important parte - the code inside success
$(".dl-menuwrapper").html("<button class='dl-trigger' style='visibility:hidden;'></button>"+json.html.replace('dl-submenu', 'dl-menu dl-menuopen'));
$('#dl-menu').dlmenu();
The json.html contains the string with the HTML to being added to the DOM. Like this:
json.html='<ul class="dl-submenu"><li data-id="17">A<ul class="dl-submenu"><li data-id="18">B<ul class="dl-submenu"><li data-id="20">C</li><li data-id="21">D</li></ul></li><li data-id="19">E</li></ul></li></ul>'

Using .on() this way only binds elements that are currently in the DOM.
Because you load the menu through AJAX, it is not available when this code is executed.
The best workaround is to select a wrapper and specify a selector:
$(".dl-menu").on("click", "li:not(:has(li)):not(.dl-back)", function(){
});
Providing .dl-menu exists in the HTML that you do not create once the document is loaded.
EDIT - Alternative
Place the code setting up the event listener after the menu is loaded.

You should use .on('click'....) on an element that's already present. So you will need to use the code like:
$(document).ready(function() {
$(".dl-menuwrapper").on("click", ".dl-menu li:not(:has(li)):not(.dl-back)", function(){
// My Code...
});
});
Or alternatively,
$(document).on("click", ".dl-menu li:not(:has(li)):not(.dl-back)", function(){
// My Code...
});

Related

Issues with jquery delegate

I'd like know how to fire unique Handler triggered by clicked element loaded dynamically in parent div (so delegate) or when is directly loaded.
Firstly, <a class="manage-lnk>Manage</a> Elements are loaded directly, but after, further there are loaded dynamically
html
<div id="viewContainer">
<a class="manage-lnk">Manage</a>
</div>
lib.js.
I have to find this tip for it to work in both cases
$(document).on('click','.manage-lnk',function(){
alert(1);
});
$('.manage-lnk').on('click',function(){
alert(1);
});
what i want is to fire alert(1) although the element is dynamically loaded or not.
(PS:Excuse me for my english i speak french)
Fire this:
$('.manage-lnk').on('click',function(){
alert(1);
});
Each time you dynamically add another one of these:
<div id="viewContainer">
<a class="manage-lnk">Manage</a>
</div>
If it's dynamically loaded after the JS has fired it will not have the event attached.
It would make sense to add it to a function you can call just after the code that dynamically adds in the HTML:
function addNewHtmlSectionFunctionName() {
//Code to add div dynamically
}
function attachClickEventToManageLnk() {
$('.manage-lnk').on('click',function(){
alert(1);
});
}
$(function() {
addNewHtmlSectionFunctionName();
attachClickEventToManageLnk();
});

Jquery Click not working in IBM Mobile first

Below is the code i have added in main.js file
$(function(){
$(".menuHorizontal div").click(function(){
console.log('hi');
});
});
Below is my html DOM structure
<div class="menuHorizontal">
<div class="yellow-borBottom">All</div>
<div>Elevators</div>
<div>Escalators</div>
<div>Walkways</div>
</div>
my jquery click function wont works, no event on click. not even it shows error in console. plz help me to resolve this
I have added a seperate Jquery file too but still wont works
The way that you have this scoped attaches an event to all div's contained within a div assigned class menuHorizontal. In the code that you posted, there are none of these!
<div class="menuHorizontal">mush be close with</div> // No divs inside here!
You closed the div with class menuHorizontal too soon. Two options below. The former will also attach the event to the "mush be close with" text, while the latter will not.
<div class="menuHorizontal">
<div>mush be close with</div>
<div class="yellow-borBottom">All</div>
<div>Elevators</div>
<div>Escalators</div>
<div>Walkways</div>
</div>
<div class="menuHorizontal">>mush be close with
<div class="yellow-borBottom">All</div>
<div>Elevators</div>
<div>Escalators</div>
<div>Walkways</div>
</div>
Were you trying to scope like this, which attaches the event to div's with class menuHorizontal?
$("div.menuHorizontal").click(function(){
console.log('hi');
You might also want to change your scope to the higher level div, like so. Google event bubbling for more info
$(".menuHorizontal").click(function(){
console.log('hi');
Also, consider using jQuery .on(), as follows. It's a little more current, and generally more flexible.
http://api.jquery.com/on/
$(function(){
$(".menuHorizontal div").on('click', function(){
console.log('hi');
});
});
$(".menuHorizontal div").click(function(){
console.log('hi');
});
This does not work because in your HTML <div class="menuHorizontal">mush be close with</div> you dont have a div inside of the div .menuHorizontal so the event is not binded on any div ( as it doesn't exist). So you can do as below.
Change your HTML to
<div class="menuHorizontal">mush be close with
<div class="yellow-borBottom">All</div>
<div>Elevators</div>
<div>Escalators</div>
<div>Walkways</div>
</div>
And the existing jquery must work fine.
And here is Working Fiddle

add simple onclick js to rails

I have a simple div in one of my views that I want to click to hide another element on the page. I put this in my application.js But it doesn't do anything. Did I put it in the wrong place?
function toggleNewPostForm {
$('.new-post-btn').hide();
}
Use document ready to make sure document is loaded before selecting an element from HTML and call your function inside
function toggleNewPostForm(){
$('.new-post-btn').hide();
};
$( document ).ready(function() {
toggleNewPostForm();
});
Try something like this
<div class="xyz">Click here!</div>
in javascript
$(".xyz").click(function(){
$('.new-post-btn').hide();
});
Also check if event listener is added after document ready method? i.e
$(function(){
$(".xyz").click(function(){
$('.new-post-btn').hide();
});
});
If this is the only js you have, there will be no click-behaviour. You have to tell the element, that is has to react to a click-event.
Try this in your application.js-file:
function toggleNewPostForm() {
$('.new-post-btn').hide();
}
$(document).on('ready page:load', function(){
$('.new-post-btn').on('click', function(){
toggleNewPostForm();
});
});
P.S.: As RGraham points out, you have to write the parameter-paranthesis if you define a function.
P.P.S.: In ruby on rails, you should check against 'ready' and 'page:load' as document-ready-handlers, because Ruby on Rails uses the "Turbolinks"-library by default.

Not working Jquery

I using comboBox Plugin.When i choose zawgyi-one in dropdown listbox, jquery not working.Why?
html
<div class="result">
<span>မြန်မာစာ(Myanmar Text)</span>
</div>
<!-- For Testing Jquery -->
<button id="click-btn">Jquery Testing Button</button>
javascript
jQuery(function($){
$(document).ready(function(){
$("#click-btn").click(function (){
alert("jquery Work");
});
});
});
DMEO LINK is http://jsfiddle.net/qq6uq7c6/11/
I have found the issue.
The combobox plugin is calling this line document.body.innerHTML=_html; when ever a select change is happening. What that does is replace the elements with clone of same elements but the problem here is it doesn't clone the events attached to it. (So i recommend not to use this plugin itself since it may kill other plugin events also).
To over come this you can use jQuery delegated event and it HAS TO BE assigned to document object or any parent object and use jQuery instead of $.
The updated code will look like
jQuery(document).ready(function(){
jQuery(document).on('click',"#click-btn",function (){
alert("jquery Work");
});
});
Here is a working fiddle.

jQuery Class selector not working

I'm struggling to make an alert come up when an anchor tag with a specific class is clicked inside of a div.
My html section in question looks like this...
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
The jQuery section is as follows..
$('.bar').click(function()
{
alert("CLICKED");
});
My problem is that I cannot get this alert to come up, I think that I'm properly selecting the class "next", but it won't pick it up for some reason. I've also tried almost everything on this page but nothing is working. If I don't try to specify the anchor tag i.e. $('#foo').click(function()... then it works, but there will be multiple anchor tags within this div, so simply having the alert executed when the div is clicked won't work for what I need. The website this is on is a search engine using ajax to send information to do_search.php. Within the do_search.php I make pagination decisions based on how many results are found, and if applicable, a next, previous, last, and first link may be made and echoed.
EDIT: I just figured it out, it was my placement of the .next function, since it wasn't created on the initial document load but instead after a result had been returned, I moved the .next function to the success part of the ajax function since that is where the buttons will be created if they need to be, now it works.
Try using the live() command:
$(".bar").live("click", function(){ alert(); });
Because you load your button via AJAX, the click event isn't binded to it. If you use the live() command, it will automatically bind events to all elements created after the page has loaded.
More details, here
.live is now deprecated and is the selected answer for this. The answer is in the comments in the selected answer above. Here is the solution that resolved it for me:
$(document).on('click','.bar', function() { alert(); });
Thanks to #Blazemonger for the fix.
You surely missed $(document).ready(). Your code should be:
$(document).ready(function(){
$('.bar').click(function()
{
alert("CLICKED");
});
});
Hope this helps. Cheers
Make sure you have included JQuery Library properly.
Make sure your script has written between $(document).ready() in short $(function(){ });
Demo : http://jsfiddle.net/W9PXG/1/
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
$(function(){
$('a.bar').click(function()
{
alert("CLICKED");
});
});

Categories

Resources