Home › Forums › JavaScript › What Am I Clicking On? — Selecting nested elements
- This topic is empty.
-
AuthorPosts
-
September 22, 2011 at 9:13 pm #34468
nilsw
MemberOk, here is the general problem, I’ve got some images nested inside a list item tag in an unordered list and I want to click on it and run a function. But I seem to be having trouble selecting it with jQuery. Also, I want to be able to grab the src attribute from the image I am clicking on and assign that to another element … like a dynamically sourced lightbox type of thing. When I put my Javascript that is called from inside the images onclick function, the click event is handled correctly, but I am unable to get the selected image’s src attribute.
function viewLargeThumb(){
var selectedImageURL = $(this).attr('src');
$('#featuredImg').attr('src', function(){ return selectedImageURL;});
$('#galleryContainer').hide(); //hide the main gallery view
$('#featuredContent').fadeIn(); //show the featured image view
}
In this situation, $(this).attr(‘src’) is returned as ‘undefined’.
But if I get rid of the ‘onclick’ attribute in the image tag, and try to select the image with jQuery, nothing happens.
$(".galleryImg").click(function(){
var selectedImageURL = $(this).attr('src');
console.log(selectedImageURL);
$('#featuredImage').attr("src", selectedImageURL);
$('#galleryContainer').hide(); //hide the main gallery view
$('#featuredContent').fadeIn(); //show the featured image view
});
Or alternately:
$("#gallery img").click(function(){
var selectedImageURL = $(this).attr('src');
console.log(selectedImageURL);
$('#featuredImage').attr("src", selectedImageURL);
$('#galleryContainer').hide(); //hide the main gallery view
$('#featuredContent').fadeIn(); //show the featured image view
});
Any ideas?
September 27, 2011 at 2:36 pm #88110nilsw
Memberanyone?
September 27, 2011 at 5:59 pm #88124Mottie
MemberAre you wrapping your javascript inside of a document ready function?
$(function(){
$('#gallery img').click(function(){ ... });
});September 29, 2011 at 6:27 pm #88251nilsw
Membersolved it…. how can I delete this thread?
September 29, 2011 at 6:40 pm #88253Mottie
MemberWhy delete when you can share so others can learn?
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.