This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
I have a webpage and it have html content with id.i am calling a function on onclick. Everything seems working if i am making changes into static content but when i am trying to call any jQuery function like html,append etc... with my dynamic content then it is not working .
As far as i understand it's because of Dom not getting updated with new content.So i would like to know how can i update dom after loading dynamic data.
A demo code below ..
jQuery( document ).ready(function($) {
var width=$( window ).width();
if(width <= 768){
$('#extraslidercontent').html("<div class='container html_mb' style='background-color:#f29a1f;width:100%;max-width: 100%;'><div class='template-page content av-content-full alpha units'><div class='post-entry post-entry-type-page post-entry-3291'><div class='entry-content-wrapper clearfix'>\
"+$('#testtt2').html()+"</div></div></div></div><div class='container css_mb' style='width:100%;max-width: 100%;'><div class='template-page content av-content-full alpha units'><div class='post-entry post-entry-type-page post-entry-3291'><div class='entry-content-wrapper clearfix'>\
"+$('#testtt3').html()+"</div></div></div></div><div class='container wp_mb' style='background-color:#493c59;width:100%;max-width: 100%;'><div class='template-page content av-content-full alpha units'><div class='post-entry post-entry-type-page post-entry-3291'><div class='entry-content-wrapper clearfix'>\
"+$('#testtt1').html()+"</div></div></div></div>");
updte();
}
after loading data in to testtt2 id i am trying to use an id which is in it's content.
Let me know if i missed anything to explain.
You will need to use event delegation for the new element.
$('body').on('click', '#some-id', function () {});
Or for older jQuery ( < 1.7)
$('body').delegate('#some-id', 'click', function () {});
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I am trying to make a follow button - and when clicked it sends an ajax request to my backend script and if it executes it returns a value that triggers the button's text to go from "follow" to "following" - and that part works just fine. But the jquery part where I send the user data in a data-attribute "data-follow" won't toggle with "data-unfollow". It only works when you refresh the browser which means you can only click the follow button, see it and the data attribute to change to "unfollow" but if you click once more it does not work. I cant figure it out and i've done my searching at the stack.
ERROR
TypeError: $(...).attr(...) is undefined
HTML
<button id="follow" data-follow="1, username1, username2">
<div><img src="images/loggedin/follow.png"></div>
<div>Follow</div>
</button>
JQuery
$("button[data-follow]").click(function(){
var button = $(this);
var data = $(this).attr("data-follow").split(",");
alert(data);
button.find(" > div:last-child").animate({opacity: "0"},200, function(){
$(this).animate({opacity: "1"},200);
$(this).html("Following");
var dataValue = $(this).closest("#follow").attr("data-follow");
$(this).closest("#follow").attr("data-unfollow", dataValue);
$(this).closest("#follow").removeAttr("data-follow");
});
});
$("button[data-unfollow]").click(function(){
var button = $(this);
var data = $(this).attr("data-unfollow").split(",");
alert(data)
button.find(" > div:last-child").animate({opacity: "0"},200, function(){
$(this).animate({opacity: "1"},200);
$(this).html("Follow");
var dataValue = $(this).closest("#follow").attr("data-unfollow");
$(this).closest("#follow").attr("data-follow", dataValue);
$(this).closest("#follow").removeAttr("data-unfollow");
});
});
$(document).on('click', 'button[data-follow]', function() {...});
$(document).on('click', 'button[data-unfollow]', function() {...});
Try it this way.
More Generic answer!
You can simply change the state of a button by removing, adding and toggling css classes via jQuery.
At (document.ready) check if follwing or unfollowed state via your ajax request and change the button's css class.
if(following){
$("#buttonID").toggleClass('following_btn');
} else{
$("#buttonID").toggleClass('unfollowing_btn');
}
Once clicked, process your code in the web service. Follow if unfollowed or Unfollow if followed. Then if you're rturning the updated state use that to re-update your button's css class accordingly. Or perform ajax call to verify the new state after the button click's ajax call finishes.
CSS:
.following_btn{
//your following style
}
.unfollowing_btn{
//your un-following style
}
Hope it helps!
This question already has answers here:
Check if image exists on server using JavaScript?
(18 answers)
Closed 6 years ago.
I am making a site with a popup. The popup is supposed to have up to 12 images in it. I am calling my images pizza1.jpg, pizza2.jpg, pizza3.jpg, and so on.
Is there any way with pure JavaScript to make the images show up only if there is actually a file with the name I have told it to look for?
This Question is similar, but all the answers are complicated, and only moderately related.
You can use onError event for remove object from your popup:
<img src="src" onError="removeElement(this);" />
Check if it will work:
function removeElement(element) {
element.remove();
}
You should handle the onerror event of the img element.
You can create an Image instance and use its onload event to see if it has loaded. If so just append the image to whatever element.
Demo
var imgurls = [
"https://placekitten.com/g/64/64",
"https://placekitten.com/g/32/32",
"https://placekitten.com/g/none/200",
"https://placekitten.com/g/100/100",
"https://placekitten.com/g/24/24"
];
imgurls.forEach(function(url){
let img = new Image();
img.onload = onImageLoad;
img.src = url;
});
function onImageLoad(){
document.body.appendChild(this);
}
<div id="container">
</div>
This question already has answers here:
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 7 years ago.
I'm trying to target a button I've created by pressing another button. My code technically works, but due to the size of what I'm doing, I'm trying to put the function of the second button press in another js file. That where I'm running into problems. My code is below.
$("#webCoding").on("click", function() {
if ( $( ".webCodingID" ).length ) {
return false;
}
picture.attr("src", "img/webCoding.jpeg");
$(".target").empty();
$(".jumbotron").hide();
var buttonGroup = $('<div role="group" aria-label="...">').addClass('btn-group-vertical center-block')
var buttonPhilosophy =$("<button type='button'>").addClass("btn btn-default btn-lg").append("Design Philosophy")
var buttonStack =$("<button type='button'>").addClass("btn btn-default btn-lg").append("Visit My Stack Overflow Account")
var buttonGithub =$("<button type='button' id='git'>").addClass("btn btn-default btn-lg").append("Look at what I've been doing on Github")
var webCodingID =$("<div>").addClass("trainingID")
$(buttonGroup).append(buttonPhilosophy).append(buttonGithub).append(buttonStack);
$('.target').append(buttonGroup).append(webCodingID);
// code for pressing created button is below.
$("#git").on("click", function() {
prompt("herro");
});
});
but I put this in another file (and get rid of the same code in the original js file), and nothing happens.
$(document).ready(function(){
$("#git").on("click", function(){
prompt("jungle boogie");
});
I can't figure out why. The js file is linked to my main page, I just can't get it to recognize buttons created by JS in another file.
You should bind the on to the body like so:
$("body").on("click", "#git", function(){
That should solve your problem I believe :)
This question already has answers here:
jQuery : how to determine that a div is scrolled down
(7 answers)
Closed 9 years ago.
I want to call ajax function while scrolling inner scroll and append the results at the bottom of the existing results.
For refrence I've attached an image here.
How can I achive this?
You can use something like this without jQuery also
window.onload = function(){
if(window.addEventListener){
document.addEventListener('DOMMouseScroll', moveObject, false);
}
var myDiv = document.getElementById("myDiv");
myDiv.onmousewheel = ajaxFunction();
}
This question already has answers here:
Turning live() into on() in jQuery
(5 answers)
Event handler not working on dynamic content [duplicate]
(2 answers)
Closed 9 years ago.
I have been using this code to get a simple lightbox working on a site of mine.
And I tried to modify it slightly so:
a) The lightbox fades in- Done
b) The script pulls in the src attribute not the href- Done
b) I can pull in data from a custom "data-description" attribute on the <img> that is being clicked (or tapped I suppose) to a <p> in the lightbox.
Issues
With the second, when the image is first clicked, It works fine. When any other is clicked, or it is clicked again, nothing happens- I can't work out why as I seem to be doing it right?
Also, when using jQuery 1.9, live() is apparently depreciated- I was using 1.8.2 before and didn't notice until now, I have tried on() with no sucess, and being a JS beginner am puzzled as to how to fix it, this issue means that the lightbox won't close.
Almost-working-but-broken code here: http://codepen.io/hwg/pen/ybEAw - Sorry about all the comments but I find it easier that way.
JS:
$(document).ready(function() { //Document Ready
$('.inner_img').click(function(e) {
//prevent default action (hyperlink)
e.preventDefault();
//Get clicked link href
var image_src = $(this).attr("src");
// Get Description
var desc = $(this).attr("data-description");
/*
If the lightbox window HTML already exists in document,
change the img src to to match the href of whatever link was clicked
If the lightbox window HTML doesn't exists, create it and insert it.
(This will only happen the first time around)
*/
if ($('#lightbox').length > 0) { // #lightbox exists
//place href as img src value
$('#content').html('<img src="' + image_src + '" />');
// Change Description in the P tag
$('.desc').html(' '+ desc +' ');
//show lightbox window - you could use .show('fast') for a transition
$('#lightbox').fadeIn(); // Fades it in
}
else { //#lightbox does not exist - create and insert (runs 1st time only)
//create HTML markup for lightbox window
var lightbox =
'<div id="lightbox">' +
'<p>Click to close</p>' +
'<div id="content">' + //insert clicked link's href into img src
'<img src="' + image_src +'" />' +
'<p class="desc">'+ desc +'</p>' + // Adds Description from <img data-description="..">
'</div>' +
'</div>';
//insert lightbox HTML into page
$(lightbox).hide().appendTo("body").fadeIn();
}
});
//Click anywhere on the page to get rid of lightbox window
$('#lightbox').on('click', function() { //must use live, as the lightbox element is inserted into the DOM
$("#lightbox").fadeOut(); // Fades it out
});
}); // End
Thanks for any help.
EDIT: I have been shown that the live/on issue is very common, I can see where I went wrong. Thanks for the assistance on this commenters.
However, why won't my code work for the second issue?
use event delegation with on -
$(document.body).on('click','#lightbox', function() {
$("#lightbox").fadeOut(); // Fades it out
});
Demo ---> http://codepen.io/anon/pen/ywJhe
You can change
$('.inner_img').click(function(e) {
to
$(document.body).on('click', '.inner_img', function(e) {
so that events occurring after the binding will still be delegated to the new elements.