This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Closed 9 years ago.
I wrote a script, which get data (in Json type) from a method and show it in div tag with a close button, when i click on close button it is not work! my script is:
$(document).ready(function () {
$("#go").click(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "WebForm2.aspx/GetMyBooks",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (var i = 0; i < response.d.length; i++) {
$("#pejiGrid").append("<div class='modal'><div style='float:left;'><span class='close'>X</span></div>" + response.d[i].BOOK_NAME + "<br/>" + response.d[i].BOOK_DESC + "</div><br/>");
};
},
});
$('.modal').hover(
function () {
$(this).find('.close').delay(0).fadeIn(300);
},
function () {
$(this).find('.close').delay(0).fadeOut(500);
});
}, 5000);
});
$('span.close').click(
$(this).closest('div.modal').fadeOut(0)
);
});
What is the problem?
EDIT : about my hover script i should say it shows the close button by delay but i gave zero to delay value :
$('.modal').hover(
function () {
$(this).find('.close').delay(0).fadeIn(300);
},
function () {
$(this).find('.close').delay(0).fadeOut(500);
});
some body can help me what is the problem?
You need to use event delegation here to bind the click event to your dynamically created div and span element inside #pejiGrid:
$('#pejiGrid').on('click', 'span.close', function() {
$(this).closest('div.modal').fadeOut(0);
});
Related
I am working on a random quote app. Quote is display when click a new quote button but I want quote already display when page loads. I invoked a function but it still does not work. Thank you!
Here is my code:
$(document).ready(function() {
function randomQuote() {
$('#get-quote').on('click', function(e){
e.preventDefault();
// Using jQuery
$.ajax( {
url: "http://quotes.stormconsultancy.co.uk/random.json",
dataType: "jsonp",
type: 'GET',
success: function(json) {
// do something with data
console.log(json);
data = json[0];
$('#quotation').html('"'+json.quote+'"');
$('#author').html('-- '+json.author+' --');
$('a.twitter-share-button').attr('data-text',json.quote);
},
});
});
$('#share-quote').on('click', function() {
var tweetQuote=$('#quotation').html();
var tweetAuthor=$('#author').html();
var url='https://twitter.com/intent/tweet?text=' + encodeURIComponent(tweetQuote+"\n"+tweetAuthor);
window.open(url)
});
}
randomQuote();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try removing click listener. inside randomeQuote() remove click listener.
keep your click listener out side of document.ready
$(document).ready(function() {
randomQuote(); // call initially and get random quote
});
function randomQuote() {
$.ajax( {
url: "https://quotes.stormconsultancy.co.uk/random.json",
dataType: "jsonp",
type: 'GET',
success: function(json) {
// do something with data
data = json[0];
$('#quotation').html('"'+json.quote+'"');
$('#author').html('-- '+json.author+' --');
$('a.twitter-share-button').attr('data-text',json.quote);
},
});
$('#share-quote').on('click', function() {
var tweetQuote=$('#quotation').html();
var tweetAuthor=$('#author').html();
var url='https://twitter.com/intent/tweet?text=' + encodeURIComponent(tweetQuote+"\n"+tweetAuthor);
window.open(url)
});
}
$('#get-quote').on('click', function(e){
e.preventDefault();
randomQuote();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="get-quote">get quote</button>
<div id="quotation"></div>
Remove the onClick listeners so that when you call the function it will update directly.
function randomQuote() {
$.ajax( {
...
success: function(json) {
... //do updates
},
});
}
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I use ajax to create dynamic div, and want to get notified when I click the "a" inside div which id='listall', but it's not working, why?
How to correct it. thanks
here is the code:
$(function(){
$.ajax({
type: "GET",
url: 'http://XXX:8080/',
dataType:'json',
contentType:"application/json",
success:function(data){
console.log(data);
var projectList="<ul style='list-style:none;'>"
for (var i = 0; i < data.data.length; i++) {
projectList += "<li><div id='listall'><a href='/projectDetail'>"+
"<img class='back' src='data.data[i]'></li>"
}
var projectList +="</ul>"
},
error:function(){
alert("connection error");
}
});
$('#listall').on('click', 'a', function (){
console.log('click!');
alert("finally");
});
});
Delegate the event
$('body').on('click', '#listall a', function (){
console.log('click!');
alert("finally");
});
you should use
$(document).on('click','#listall a',function(){
console.log('click!');
alert("finally");
});
I am learning jquery and i am stuck with a problem. Here is the code
$(function(){
var gotProducts=new Array();
var productsWithDelete=new Array();
$('.addProducts').on('keyup',function(event) {
var searchVal=$(this).val().trim();
if(searchVal.length > 0) {
$.ajax({
url: 'http://localhost/url',
data: { products: $(this).val(), },
type: 'POST',
dataType: 'html',
success: function(msg) {
$('#printTheProducts').html(msg);
}
});
}
});
$('.productsButton').click(function() {
alert('yes');
});
});
The response I am getting from the ajax call is a button having class productsButton.
Now when i try to click that button I got through ajax then it does not alert yes. I mean it does nothing.
Question:-
What might be the problem?
Try event delegation using .on() for generated button, As they are generated dynamically
$('#printTheProducts').on('click','.productsButton',function(){
alert('yes');
});
Where #printTheProducts is the closest parent element, you can use document or document.body also as a selector!
Syntax:
$(closestparentelement).on('event','targetselector',function(){
});
I have the following JQuery code :-
$('.rpItem').on("click", "img", function (e) {
alert('here');
var text = $(this).siblings('span.rpText').text();
e.preventDefault();
e.stopPropagation();
var args = {
reportName: text
};
$.ajax({
type: "POST",
url: "Dashboard.aspx/AddToFavourites",
data: JSON.stringify(args),
contentType: "application/json;charset=utf-8;",
success: function (data) {
__doPostBack('#MainMenuUP', text);
//__doPostBack('<%= MainMenuUP.ClientID %>', text);
},
error: function () {
}
});
});
$("#reports_textSearch").keyup(function () {
var textLength = $(this).val().length;
delay(function () {
if (textLength == 0) {
emptySearchString();
}
if (textLength > 2) {
var args = {
reportName: document.getElementById('reports_textSearch').value
};
doSearchString(args);
}
}, 1000);
});
function doSearchString(args) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Dashboard.aspx/FetchReports",
data: JSON.stringify(args),
dataType: "json",
success: function (data) {
//__doPostBack('#MainMenuUP', data.d);
__doPostBack('<%= MainMenuUP.ClientID %>', data.d);
},
error: function (data) {
}
});
}
and the first time its working fine. However after the postback, the doSearch keeps on working correctly, whilst the
$('.rpItem').on("click", "img", function (e) {
fails. It is not even going through that code.
I tried to replace the
__doPostBack('<%= MainMenuUP.ClientID %>', data.d);
with
__doPostBack('<%= MainMenuUP.UniqueID %>', data.d);
but that just does a page refresh which I do not want.
Any help will be very much appreciated!
Thanks
Change your selector to this one:
$('body').on("click", ".rpItem img", function (e) {
// your code
});
If the .rpItem is replaced during your ajax call read the following:
The first time your js executes, it binds the on event to the existing rpItems.
Any new added .rpItemwill skip this binding unless you re-execute the script that accomplishes the binding.
In order to avoid this, you may use the document for the binding as #Mojtaba suggests but keep in mind that you "add" the binding to the document leading to "checking" whether an .rpItem img has been clicked or not every time something is clicked on the document.
Otherwise, you can create a function that will take your .rpItem as an argument and will accomplish the binding explicitly. After each new .rpItem added to your page, you can call this function to bind the click event. Ex:
function foo(arg) {
$(arg).on("click", "img", function (e) {
...
}
}
$(document).ready(function(){
$('.rpItem').each(function(){
foo($(this));
};
});
im trying to turn this jquery script into a toggle event type, thier is my script, with illustrations, to show what i want to happen. i cnt seem to intrgate it so here goes:
//myElement.toggle(vote(), unvote()); // this is the toggle event
$(document).ready(function() {
$('.statuses').delegate('.vote_up', 'click', function(e) {
//stop event
e.preventDefault();
//get the id
var the_id = $(this).closest('.message').attr('id').split('_').pop();
//function vote () // this should be the vote up function
//the main ajax request
$.ajax({
context: this,
type: "POST",
// Make sure "this" in the callback refers to the element clicked
data: "action=vote_up&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
$(this).siblings("span.vote_count").html(msg).fadeIn();
// get the child <img> and set its src
$(this).children("img").attr("src", "img/uparrowActive.png");
}
});
//function unvote() thier should be another function here to unvote toggle
$.ajax({
context: this,
type: "POST",
// Make sure "this" in the callback refers to the element clicked
data: "action=vote_down&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
$(this).siblings("span.vote_count").html(msg).fadeIn();
// get the child <img> and set its src
$(this).children("img").attr("src", "img/uparrow.png");
}
});
});
i just dont know how to integrate this toggle event into this jquery snippet, someone please help me ive been trying for years :)) thanks
Doing so:
$('.statuses').delegate('.vote_up, .vote_down', 'click', function(e) {
if($(this).hasClass('.vote_up') {
src = "img/uparrowActive.png";
action = "vote_up";
}
else {
src = "img/uparrow.png";
action = "vote_down";
}
$.ajax({
context: this,
type: "POST",
// Make sure "this" in the callback refers to the element clicked
data: "action=" + action + "&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
$(this).siblings("span.vote_count").html(msg).fadeIn();
// get the child <img> and set its src
$(this).children("img").attr("src", src);
}
});
});
$('.statuses').delegate('.vote_up, .vote_down', 'click', function(e) {
var parent = $(this).closest('.statuses'),
vote = (($(this).hasClass("vote_up")) ? "up" : "down");
if(parent.data("vote") == vote) {
return true; // If already voted up, do nothing, if already voted down, do nothing...
}
if(vote == "down") { // Vote down
src = "img/uparrow.png";
action = "vote_down";
}
else if(vote == "up") { // Vote up
src = "img/uparrowActive.png";
action = "vote_up";
}
// Setting current vote (up or down)
// So next time you toggle, we have the trace of the previous vote (up/down)
// And authorise only do the opposite
parent.data("vote", vote);
$.ajax({
context: this,
type: "POST",
// Make sure "this" in the callback refers to the element clicked
data: "action=" + action + "&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
$(this).siblings("span.vote_count").html(msg).fadeIn();
// get the child <img> and set its src
$(this).children("img").attr("src", src);
}
});
});