Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript What Am I Clicking On? — Selecting nested elements

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #34468
    nilsw
    Member

    Ok, 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?

    #88110
    nilsw
    Member

    anyone?

    #88124
    Mottie
    Member

    Are you wrapping your javascript inside of a document ready function?

    $(function(){
    $('#gallery img').click(function(){ ... });
    });
    #88251
    nilsw
    Member

    solved it…. how can I delete this thread?

    #88253
    Mottie
    Member

    Why delete when you can share so others can learn?

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.