how to handle click event on dynamic content? - javascript

i have this HTML code on a page when my page loaded:
<div class="divmain">Add
<span class="spn">123</span>
</div>
when you click on that span it will create another span and show hi alert to you,
when the page loaded for the first time it works fine and write another span on that dive as the same the old span but after that if you click on the new span it works not.
i did some test and found if i add this code :
$('.spn').on("click", function (e) {
showalert(this);
});
on the "spanwriter" function it will works , i mean if that function be like this:
function spanwriter(master) {
var rows = '<span class=\'spn\'>123</span>';
$('.divmain').html(rows);
<------- this event must be add here until it --------------->
$('.spn').on("click", function (e) { works
showalert(this);
});
}
why i should add click event at the end of wrote content until span can get that event and works?
i used jquery-1.10.2.js on my sample
my all codes are:
$(function () {
$('.divmain').on("click", function (e) {
spanwriter(this);
});
$('.spn').on("click", function (e) {
showalert(this);
});
});
function spanwriter(master) {
var rows = '<span class=\'spn\'>123</span>';
$('.divmain').html(rows);
}
function showalert(master) {
alert("hi");
}

you have to do the same but with document.on("click")
$(document).on("click", ".buttonClass", function() { console.log("inside"); });
$('.divmain').on("click" make a kind of binding when document is loaded, so when you add dynamix elements to the dom it is noit catched. Whith the use od document.on, it works even if you add dynamic content to the document.

The simplest and best solution to your problem is to attach the event listener to a parent element in the dom and pass the second parameter of the on() method as described in the jQuery documentation (http://api.jquery.com/on/)
In other words you should have something along the lines of:
$('body').on("click", ".spn", function (e) {
showalert(this);
spanwriter(this);
});
and then have the spanwriter() add the new span to the parent of the element it's been called upon.
I hope this is what you were looking for and answers your question.

Related

Firing a function with a newly added class

I've tried to simplify it, simple enough to make my question clearer.
The alert 'I am a boy' didn't popup with even after the addClass has been executed.
Here is my code:
$(".first").click(function () {
var a = $(this).html();
if (a=='On') {
$(this).removeClass('first').unbind().addClass('second');
$(this).html('Off');
}
});
$(".second").click(function () {
alert('I am a boy');
});
<button class="first">On</button>
This behavior is because you are apply a class to an element after the DOM has loaded, in other words dynamically. Because of this, your event listener attached to the control for '.second' isn't aware of the newly added class and doesn't fire when you click on that control.
To fix this, you simply need to apply your event listener to a parent DOM object, typically $(document) or $('body'), this will ensure it is aware of any children with dynamically added classes.
As George Bailey said, you can refer here for a in depth explanation.
In regards to your specific code, the fix is to simply adjust it as so:
$(".first").click(function () {
var a = $(this).html();
if (a=='On') {
$(this).removeClass('first').unbind().addClass('second');
$(this).html('Off');
}
});
/* Changed this:
$(".second").click(function () {
alert('I am a boy');
});
*/
// To this:
$(document).on('click', '.second', function () {
console.log('I am a boy');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="first">On</button>
The function you pass to $.post doesn’t run until later (a callback). So the class is added after you try to select it. Do it inside the callback, the same way you added the class (and you don’t need to select that class, just use $this)

javascript events not working with dynamic content added with json

I'm stuck with a situation where my DOM elements are generated dynamically based on $.getJSON and Javascript functions for this elements are not working. I'll post some general idea on my code because I'm looking just an direction of what should I do in this situation.
site.js contains general features like
$(document).ready(function() {
$('.element').on('click', function() {
$(this).toggleClass('active');
});
$(".slider").slider({
// some slider UI code...
});
});
After that:
$.getJSON('json/questions.json', function (data) {
// generating some DOM elements...
});
I have also tried to wrap all site.js content into function refresh_scripts() and call it after $.getJSON() but nothing seems to be working.
Firstly you need to use a delegated event handler to catch events on dynamically appended elements. Then you can call the .slider() method again within the success handler function to instantiate the plugin on the newly appended content. Try this:
$(document).ready(function(){
$('#parentElement').on('click', '.element', function() {
$(this).toggleClass('active');
});
var sliderOptions = { /* slider options here */ };
$(".slider").slider(sliderOptions);
$.getJSON('json/questions.json', function(data) {
// generating some DOM elements...
$('#parentElement .slider').slider(sliderOptions);
});
});
Instead of calling on directly on the element, call it on a parent that isn't dynamically added and then use the optional selector parameter to narrow it to the element.
$('.parent').on('click', '.element', () => {
// do something
});
The difference between this and:
$('.element').on('click', () => {});
is with $('.element').on(), you're only applying the listener to the elements that are currently in that set. If it's added after, it won't be there.
Applying it to $(.parent), that parent is always there, and will then filter it to all of it's children, regardless when they're added.
the easiest way is to add this after you add/generate your DOM
$('script[src="site.js"]').remove();
$('head').append('<script src="site.js"></script>');
of course your js function that generates DOM needs to be on another file than your site.js

Image not clickable after loaded via AJAX

I have a set of images that are loaded via jQuery AJAX. For some reason, my click handler won't trigger when it is clicked.
JavaScript:
$(document).ready(function()
{
$('img.delete_related_sub').click(function()
{
alert('testing');
});
//I added this part to test, because the above wasn't working...
$(document).click(function(event)
{
alert(event.target.tagName+' '+event.target.className);
});
});
HTML:
<img data-rsid="2" class="delete_related_sub" src="image.png" />
So my 2nd click handler alerts me with "IMG delete_related_sub". But the first one isn't triggered. The is actually in a table that is actually in a pane run by bootstrap tabs, not sure if that'd actually help though.
Try it like this
$(document).on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Just replace document with a static parent of your image.
Use this:
$("body").on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Or, in the success: give this:
$('img.delete_related_sub').click(function() {
alert('testing');
});
Because the line to bind the event runs before the element is added, try using
$(parent).on('click', 'img.delete_related_sub', function() {});
where the parent is a static element that will be there for sure. This works because the event is bound to an element that actually exists, then checks to match your selector. See .on() for more details.
Something like
$(document).on('click', 'img.delete_related_sub', function() {});
would work fine.
$('.delete_related_sub').live("click", function()
{
alert('testing');
});
Use live event to listen clicks

Calling the inline JavaScript on a link using jQuery

I am modifying an ancient table which has inline JavaScript in the form of <a href="javascript:<lots of shit>">. The inline JavaScript works, but it would take months to rewrite it so that it fits my assignment, which is when an outer element is clicked the inline JavaScript should be executed.
I'm sorry if I'm not making any sense, but I have been as thoughtful as to provide a fiddle. (The table aspect shouldn't matter.) TL;DR: when I click one of the colored div's I would like its inner alert() to execute and how do I do that?
Edit. Also, the link is actually hidden!
Edit #2. And, as for now, none of the HTML should be tampered with. Only jQuery/JavaScript.
Edit #3. I've updated the script to work with my table. The inner <span> is now not needed, I can select the <a> directly. Now I would just like to know if I'm using stopPropagation() correctly?
Code:
$(function () {
$('table.result-v2 tr.view').bind('click', function () {
var $this = $(this),
$next = $this.next();
if ($next.attr('class') == 'detail') {
var $buttons = $this.find('td.buttons'),
$link = null;
if ($next.css('display') == 'none') {
$link = $buttons.find('a.show-link');
} else {
$link = $buttons.find('a.hide-link');
}
if ($link != null) {
eval($link.attr('href')); // evaluate found link
$link.bind('click', function (event) {
event.stopPropagation(); // is this needed when the link never can be clicked (it's hidden)?
});
}
}
});
});
Here is a quick hack that made your code work. And just to note that this is totally not how it should be done!
http://jsfiddle.net/2QaUX/1/
Instead of triggering a click, evaluate the inline script inside the href attribute:
Old:
$(function () {
$('.foo').bind('click', function () {
$(this).find('.bar').parent().trigger('click');
});
});​
New:
$(function () {
$('.foo').bind('click', function () {
eval($(this).find('.bar').parent().attr('href'));
});
$('.bar').parent().bind('click', function (event) {
event.stopPropagation();
});
});​
just place that js whithin a function
function clikEvent(ele)
{
//<lots of shit>
}
and call it on onclick and replace href js with void like
<a href="javascript:void(0)" onClick='clikEvent(this)'>
you have to also tack care of the data passed I have placed parameter ele wich will point the href so you can retrive id of or any other thing
if you want to use jQuery
$('#idofAtag').click(function(){//<lots of shit>});
There are two issues here. One is event propagation. When you click the div, you trigger a click on the link, which is also a click on the div. This creates an infinite loop which will quickly exceed the maximum call stack size. To get around this, you need to do two things:
Only execute the window.location.href assignment if the user clicked on the div and not the a within it.
If the user DOES click on the a, prevent the event from bubbling up to the div
The second issue is that the 'click' event on a link won't execute javascript stored in an href attribute. what you want to do is set window.location.href.
$('.foo').on('click', function (e) {
var link = $(this).find('.bar').parent('a');
if(e.target != link.get(0)) {
window.location.href = link.attr('href');
}
});
$('.foo').on('click', 'a', function(e) {
e.stopPropagation();
});
Here's a demo
--- jsFiddle DEMO ---
- NOTE - I would strongly recommend finding another way to handle this situation, but if you cannot alter the existing links, this option is viable.

Adding a function to onclick event by Javascript!

Is it possible to add a onclick event to any button by jquery or something like we add class?
function onload()
{
//add a something() function to button by id
}
Calling your function something binding the click event on the element with a ID
$('#id').click(function(e) {
something();
});
$('#id').click(something);
$('#id').bind("click", function(e) { something(); });
Live has a slightly difference, it will bind the event for any elements added, but since you are using the ID it probably wont happen, unless you remove the element from the DOM and add back later on (with the same ID).
$('#id').live("click", function(e) { something(); });
Not sure if this one works in any case, it adds the attribute onclick on your element: (I never use it)
$('#id').attr("onclick", "something()");
Documentation
Click
Bind
Live
Attr
Yes. You could write it like this:
$(document).ready(function() {
$(".button").click(function(){
// do something when clicked
});
});
$('#id').click(function() {
// do stuff
});
Yes. Something like the following should work.
$('#button_id').click(function() {
// do stuff
});

Categories

Resources