Selecting the content of a clicked element with jquery/javascript

I using WordPress to display a list of thumbnails which will load a page when clicked using AJAX. I’m using a hidden div to store the page name of the particular thumbnail, like this:

<div class="load_image">
  <div class="image_path" style="display:none">portfolio-1</div>
  <img src="..here is the thumbnail source" />
</div>

And here is the AJAX code:

Read More
var ajax_load = "<img src='img/load.gif' alt='loading...' />";
    var loadUrl = "ajax/load.php";
    $(".load_image").click(function(){
            //Get the hidden-div-content from class image_path.....somehow
        $("#ajax_result").html(ajax_load).load("<?php bloginfo('url') ?>/image_path");
    });

How would I go about getting the content of the hidden div when clicked so I can pass it to the AJAX call?

Related posts

Leave a Reply

4 comments

  1. You can use this as a reference to the element clicked, then wrap it in a jQuery object and use .children('.image_path') to get the hidden div, and then .html() to get its content.

    $(".load_image").click(function(){
        var hidden_content = $(this).children('.image_path').html();
        $("#ajax_result").html(ajax_load).load("<?php bloginfo('url') ?>/image_path");
    });
    

    Or perhaps better would be to store the data as a custom attribute using HTML5 data- attribute.

    <div class="load_image" data-hidden="portfolio-1">
      <img src="..here is the thumbnail source" />
    </div>
    

    Then use jQuery’s .data() method to retrieve the data.

    var hidden_content = $(this).data('hidden');
    
  2. There is a callback method as a parameter:

    $("#ajax_result").html(ajax_load).load("/image_path", function(val){
         //val contains what is returned
         $('jquery_selector').html(val);
    });

    take a look at the jquery docs here

  3. You should just use links and use the click event to intercept the default behavior and then perform your AJAX call.

    <a href="/full-image.jpg" class="remote"><img src="/thumb-image.jpg"></a>
    

    And then…

    $('a.remote').click(function(){
      $('#result').load($(this).find('img').attr('src').replace('thumb', 'full'));
      return false; // prevent the browser from following the link
    });
    
  4. In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned. Consider this code:

    $('div.demo-container').html();
    

    this a from jquery html() docs

    http://api.jquery.com/html/