Calling IDs and Classes inside a Javascript String - javascript

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);

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/

JQuery class selector isn't working

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()+"' />");

Javascript Event Handlers on elements appended after document is ready

I have a javasript function that should change the value of an element appended after document is ready.
What I mean is: If the javascript appends a div like: <div class="new-div"></div>, I cannot intercept actions on that DIV.
This code does not work:
$(document).ready(function() {
$('.new-div').on('click', function(){
alert('clicked');
});
});
But this code, using delegate, works fine:
$(document).ready(function() {
$(document).on('click', '.author-profile-articles-table', function(){
alert('clicked');
});
});
However, when the scroll event is needed, the following code does not work:
$(document).ready(function() {
$(document).on('scroll', '.author-profile-articles-table', function(){
alert('scrolled');
});
});
According to t.niese, scroll events do not propagate through DOM, so one can't use it with delegate to make this work.
Script tags along with the html do work but I don't feel it is an elegant/smart way.
The question is, if a scroll intercepter does not work with DOM, is that a way to put the event interceptors from a separate javascript file or the html script tag is the only option?
Cheers,
I made it work using the bind tag:
When I finished performing a given action, a trigger an event using:
$.trigger('eventName');
Than I build the event listener using bind:
$(document).bind('eventName', function(){
// Do your stuff here.
}
It works smoothly =)

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.!
});

JQuery Click - activate parent

<div class="myShips" id="161">
<img src="img/ships/red/sc.png" id="Ship161"
style="-webkit-transform: rotate(45deg);">
<div class="hpBarRed"><div class="hpBarGreen" style="width:15px;">
</div></div>
</div>
I wish to have a JQ click function, that will do something with the ID of the .myShips div I click. However, the image inside the div is the same size of that div, so it is above it. So basically I want to be able to click anywhere in that div, and activate the function (the alert and append are just for testing):
$( '.myShips' ).click(function() {
$("#hello").append("/*/");
//alert($(this).attr('id'));
});
I tried putting a larger z-index of the .myShips class but that did not work. what is my best option? Will I have to add another class for the images and then have 1 of possible 2 functions being called?
EDIT:
The problem is with absolute positioning. .myShips is inside another div that is absolutely positioned. I added the same function for click, but for ALL divs that are clicked. So when I click an image, its ID is not alerted, neither is the .myShips id alerted, but its parent id is alerted, and then 2 more divs that are its parents are alerted.
So I believe the prblem is with position: absolute
make sure the image is not <img src="img/ships/red/sc.png" id="Ship161" /> is not set to position absolute.
thats the only way how i can see this issue possible.
As long as the click event isn't being captured by the image, the event would propagate up the dom, and trigger your handler.
If, however, there is a click handler on the image, and for some reason that cannot be refactored, you can change the z-index, assuming you set the image position to relative or absolute.
http://codepen.io/anon/pen/BycJz
You need to make sure you wrap your click function in a $(document).ready() wrapper.
A page can't be manipulated safely until the document is "ready."
jQuery detects this state of readiness for you. Code included inside
$( document ).ready() will only run once the page Document Object
Model (DOM) is ready for JavaScript code to execute.
And, to be safest, I'd go with .on() to check for the click.
The .on() method attaches event handlers to the currently selected set
of elements in the jQuery object. As of jQuery 1.7, the .on() method
provides all functionality required for attaching event handlers.
To go off of #jerrylow 's example: http://jsfiddle.net/DPDxz/2/
$( document ).ready(function() {
$(document).on('click', '.myShips', function () {
alert('here');
});
});
You would use the closest() function in jQuery to find the upper parent for a DOM element when the image is clicked.
$( document ).ready(function() {
$('.myShips img').click(function(e){
var image_id = $(this).attr('id');
var ship_id = $(this).closest('.myShips').attr('id');
console.log("ship:"+ship_id+" image:"+image_id);
});
});

Categories

Resources