<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);
});
});
Related
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/
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);
I have a div that is duplicated when a button inside that div is clicked. Each duplicated div also contains a button that should duplicate the div. Right now, only the original div "duplicate" button works. I need each button to duplicate the div which contains the button. Here is the my jQuery.
$(function() {
$('.duplicate-button').each(function() {
$(this).click(function() {
$(this).closest('.desking-finance').clone().appendTo('.extra-finance-lease');
});
});
});
The problem is with the execution of this function. It only targets existing elements and not potentially new elements that may be created.
In order to have this function execute on click for every (new or old) div, use live to target them. Here is the refactored code:
$(function() {
$(document).on('click', '.duplicate-button', function() {
$(this).closest('.desking-finance').clone().appendTo('.extra-finance-lease');
});
});
I used document to bind the click handler but try and use a closer parent element relative to the duplicate-buttons. Perhaps some container div.
There was no need for $.each since $(this) will target the targeted element that triggered the event.
https://dl.dropboxusercontent.com/u/63617776/Capture.PNG
So as on the image, when you click on the map, a div is changed. Now when I click on a link in the div, I want the google maps div to change to another map.
But, the code I wrote either doesn't trigger at all or it triggers when I click anywhere on the page.
$('#nowydwor').ready(function(){
$(this).click(function(){
alert('foo');
});
});
Ofcourse the link looks like this:
{a id="nowydwor"} text {/a} (for some reason i couldn't enter < so I replaced it with {)
This triggers when user clicks anywhere on the page, for some reason. Also this is only a testcode for now, it is meant to display the alert. :) Any ideas?
EDIT: The link is contained in .html(), in a switch() statement.
case '#mazowieckie':
$('#info').html("CONTENT </h5><hr><strong><a id='nowydwor'>Skład Nowy Dwór Mazowiecki</a></strong> CONTENT");
break;
Calling ready only makes sense if you call it on the document/window to get notified as soon as the DOM is ready.
Try to bind the click handler on your DOM element directly:
$('#nowydwor').on('click', function(){
alert('foo');
});
I think what you were trying to do, is assign the click handler after the content of #info has changed. Unfortunately .ready() is only an event handler for the document ready event. It only fires once. Also changing the html of '#info' isn't triggering any events (IMHO).
You can work around this, using the .on-method on a parent element. Consider this html structure:
<div id="info">
<!-- This content is dynamically loaded -->
<a id="nowydwor">Click this to change map</a>
<!-- End of dynamic content -->
</div>
This makes it possible to call:
$('#info').on('click', '#nowydwor', function(){ /* Change map here... */ })
This assigns the event handler to #info, which is only called if the clicked element matches '#nowydwor'. Since '#info' is never removed, only the content changes, you don't have to apply it again.
The only point is, you have to determine what the id of the map/place is, because the event handler will be the same for all links.
I have a couple of Divs in my page with CSS class="hello"
Further I use Ajax to fetch a few more Divs with a CSS class="hello"
I have a piece of code which is called on Click event of the Divs as follows:
$('.hello').click(function(){
alert("Hello Clicked");
})
It works fine with the Divs that are present in my page from start but does not work with Divs loaded using Ajax. Is there something I need do in order to bind this little piece of code with the newly loaded Divs too?
you should use .on to bind the handler to another element that is already present during the execution of the binding, like say the <body>, or the document and have it detect the children events. but ideally, you should bind it to the nearest common parent of the content loaded.
demo
//bind to the body a "click" handler for elements that have class names of "hello"
$('body').on('click','.hello',function(){
alert("Hello Clicked");
})