JQuery class selector isn't working - javascript

I'm trying to select an element based on its class (using $(".class")) and I'm having an issue, and I'm not sure why it's happening.
First off, the element is an image. It gets created when a function is executed by:
$("#container").append("<img class='removeIcon' src='images/remove.png' remove='"+$(this).val()+"' />");
This works as it should. The image is added when the function is fired, even multiple times. And the value of each is what it's meant to be, it's all good. The element is fine.
What isn't working...
$(".removeIcon").click(function() {
alert();
console.log("Clicked!");
});
I'm not sure if it's not working because the image is added later, or maybe I'm doing something wrong? But I whenever I click any of the images with that class, there's no alert dialog, and no console log.
I've typed, into console, $(".removeIcon"); - and it shows all of the images with that class, so I don't understand what's wrong. Can you not have a click even on a class selector?
Thanks in advance!

your code only works for existing .removeIcon elements.
if you do add dynamic elements, try use .on
$("#container").on('click', '.removeIcon', function() {
alert();
console.log("Clicked!");
});
which binds click event on all .removeIcon elements inside #container
(including dynamic added elements)

Yes, the problem is that it is being added later, so you have to delegate with:
$("#container").on('click', '.removeIcon', function() {
alert();
console.log("Clicked!");
});
So, the event will be asigned to the container but will act on .removeIcon items.
For more info check jQuery's on function.

click() function doesn't work with dynamically loaded data.
You have to capture click event by DOM or by making onclick function
by DOM
$("#container").on('click', '.removeIcon', function() {
console.log("click");
});
OR onclick function
$("#container").append("<img class='removeIcon' onclick="somefunctionInJS()" src='images/remove.png' remove='"+$(this).val()+"' />");

Related

How can I either target an Appended element using Jquery or Javascript, or how can I add that appened element to the DOM?

I've looked all over the internet with everyone giving the same answer
$(document).on('click', '#targetID', function() {
// do stuff
});
instead of
$('#targetID').click(function() {
// do stuff
});
This is nice and it works fine, if you have a click event. But within that on click function, the part where it says do stuff, how can I now target an appended element? For instance say I append 2 divs back to back.
<div id="mainDiv"></div>
<script>
socket.on('event', function (data) {
$('#mainDiv').append ('<div class="1st" id="'+data.id+'">one</div>
<div class="2nd" id="'+data.id+'">second</div>');
});
$(document).on('click', '.1st', function() {
//and right here i would like to`enter something like
$('.2nd').css('background-color','yellow');
}
</scirpt>
This however seems not to work because to my knowledge, this element hasn't been added to the DOM. So what should I do? Should i use angular.js for this?
PS I've also tried adding the entire appended content into a variable first before appending that variable. and then using variable.find to find the element within to no avail. The variable only has context within that function, but is null in the on click function. Thanks in advance for any information that broadens my understanding of this.
The delegation of 'on' is correct. Once the div element exists in the dom, clicking should work. My only concern is you have named your classname beginning with a number. Maybe name it with an alpha character followed by a number.
The difference between the 2 is the concept of event binding vs event delegation.
$('#targetID').click(function() { is event binding which works on elements as long as they exist in the markup when the page or document loads.
$(document).on('click', '#targetID', function() { is event delegation which means the event would listen to the document for the click event on the element with ID targetID if it exists in the DOM when the page loads or if it is dynamically added.
So In your case, its event delegation since you are dynamically adding the elements. But in order to make it work, you need to register the listener on the document ready event for the document to listen to the event on the element #targetID
<script>
$(document).ready(function() // Add this
{
socket.on('event', function (data) {
$('#mainDiv').append ('<div class="1st" id="'+data.id+'">one</div><div class="2nd" id="'+data.id+'">second</div>');
});
$(document).on('click', '.1st', function() {
//and right here i would like to`enter something like
$('.2nd').css('background-color','yellow');
});
});
</script>
Here's an example : https://jsfiddle.net/nobcp0L7/1/

Calling IDs and Classes inside a Javascript String

I have this jQuery code. What it does is when you click a div button (#logogo), it shows a resized image in the stage.
$(document).ready(function(){
$("#logogo").click(function(){
$(this).addClass("active");
$("#bannergo").removeClass("active");
$("#innerstage").html("<img id=\"magiclogogo\" src=\""+document.getElementById("logogo").title+"\">").hide().fadeIn('fast');
});
});
What I want to happen next is that when you click on the image (hence the magiclogogo id), it would be able to show (or to load) the image in its original size.
So far I tried putting an id and tried to make a jquery function for it but it does not work.
If it's not possible, is there any probable way to be able to zoom the image to its original size?
$(document).on("click", "#magiclogogo", function(){
// your code here
});
So, what I'm guessing is that somwhere else you have something like:
$('#magiclogogo').on('click', function() {
//More code here...
}
If the dom element isn't loaded yet, then it will not attach the event correctly. In other words, the event must be attached once the DOM element has been loaded or attach the event to the parent and look out for the source of the event (jquery has a shorthand for this, which is the other answer).
You can use the jQuery constructor to create the element and then attach the event.
var image = $("<img id=\"magiclogogo\" src=\""+document.getElementById("logogo").title+"\">");
image.on('click', function(){
//Your code here
});
You then can add it to your container with append.
$('#innerstage').append(image);

How to get Id of hyperlink on click which was appended using jquery

I am appendend a hyperlink to the html page using append() method, It is a list of hyperlinks, and I get all other elements id by this.id, but am not able for the appended row, why this happening? is there any other way to append ??
thanks in advance
It sounds like somewhere in your code you have this:
$("selector for links").on("click", function() {
// Using this.id here
return false; // Since they're links I assume you do this or e.preventDefault();
});
and after that code runs, you add another link, but clicking it doesn't trigger the handler above. That's because the code above hooks the event on the elements that exist as of when it runs; since the link you add didn't exist, its click event didn't get hooked.
You can use event delegation to solve this, by changing the code above to:
$("selector for container").on("click", "selector for links", function() {
// Using this.id here
return false;
});
That hooks click on a container that holds the links, but fires the handler as though the event had been hooked on individual links. So since the event is hooked on the container, you get the event even when you add new links.
Concrete example:
$(document).on("click", "a", function() {
alert(this.id);
return false;
});

Chain a div click to another with jquery?

Not sure if I'm using the correct lingo,
But I want to click a div and when I do it should cause another to be clicked after.
Ex click div 1 then div 2 gets clicked (but not by user, just by JS)
Is this possible?
There is already a huge function attached to div 2 when clicked, so I need to to link the two if that makes sense. Easier hopefully than sorting through lots of code and trying to add it in.
Any help?
you can use:
$('#div1').click(function(){
$('#div2').trigger('click');
})
You can just call click() on div 2:
$('#div1').click(function(){
//your code
$('#div2').click();
});
$("#div1").click(function() {
// Do stuff...
// Then click the other DIV
$("#div2").click();
}
It is possible, in the click handler for div one call
$("#div2").click();
Yes this is possible creating the function for the click on the 1.
With
$('#iddiv1').click(function(){
//your code
$('#iddiv2').click();
});
Documentation
Yes you can by doing so:
$("#idDiv1").click(function(){
//do what you want
$("#idDiv2").trigger("click");
}
You need to have an onclick event TRIGGER a click on another div.
$('#foo').click(function() {
$('#bar').trigger("click");
});
$('#bar').click(function() {
// Do something
});
$('#div1').click(function() {
$('#div2').click();
});
Edit:
This solves your problem because it attaches a listener to div1 and executes a function whenever div1 is clicked. It just so happens that you want to emit another event for div1, which, in jQuery shorthand, is written with the .click() function.
Giving .click() a function as a parameter sets the callback for the click event, which can manually be called by calling the function without any parameters.

jquery event functions not working properly

I have a page where the contents displayed from database using jquery and ajax. There are lot of processes in the page like Adding new content and image, Editing, Deletion etc and all are using ajax. But now some of event functions like click , mouseenter are not working in the content which where displayed from the database.
for example: This is how i display images in the page
for(var i=0;i<images.length;i++)
{
$("#content").append("<img src='"+images[i]+"' class='img' width='300' height='200' />");
}
Images are displayed properly. but when trying to do somthing on click event in images like this, its not working
$("#content .img").on('click',function()
{
//here comes my process, but its not working
}
Please help me to solve this problem.
Try:
$("#content").on("click", ".img", function() {
});
The problem is that $("#content img") creates a jQuery collection of elements that exist at the time it is run. When you start dynamically adding new elements, they don't have the event listener applied to them automatically.
What $("#content").on("click", ".img") does is provide for event delegation. So what's really happening is an event listener that is applied to $("#content") but only fired when that event comes from a descendant with a matching selector (.img in this case).
More info at http://api.jquery.com/on/.
Try like this
$(document).on('click', '#content .img',function()
{
...
});
This problem will always arise when you are trying to add some dynamic content. So,to resolve this always keep in mind some point.
All use some static element to reference the dynamic you are trying to apply event on.
Example : in your case try using
$("#content").on('click', 'img', function(){
//try using this way make your code works fine.!
});

Categories

Resources