Dave
Dave

Reputation: 420

Removing part of an image src

Using jQuery, I've created a simple lightbox which loads an image upon clicking a thumbnail.

I'm trying to get the lightbox to work by storing the thumbnail src as a variable from which to load the main gallery image. The variable however, needs the '/thumbs' part of the src removing to find the larger gallery image.

I've followed numerous answers already given to variants of this question, but none of my attempts to emulate the results seem to work.

I've gotten as far as this:

$("#attractions-dave li a").live("click", function showAttraction(e){

 var example = $(this).children('img').attr('src', $(this).children('img').attr('src').replace('/thumbs',''));      

});

For reference, the associated html is:

<ul id="attractions-dave">
 <li>
  <a href="../attractions/attractions.php">
   <img src="../images/photos/bouncy-castles/thumbs/happyclown.jpg" alt="happy clown castle" />
  </a>
 </li>
</ul>

Once I have got the variable, I am using it to set a background image, using the following code:

$('#example').css('background-image', 'url(' + example + ')');

As of now, the code simply doesn't add any background css to the element.

I'm not receiving any errors with this code, but it's clear that the variable (the amended thumbnail src) isn't being recognised.

If anyone can see where I'm going wrong, then any help would be much appreciated.

Upvotes: 0

Views: 1869

Answers (2)

David Hellsing
David Hellsing

Reputation: 108500

example in your code is a jQuery object. You need to do:

var example = $(this).children('img').attr('src').replace('/thumbs','');

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

I think you need to prevent default behaviour:

http://jsfiddle.net/eYJ7L/

$("#attractions-dave li a").live("click", function showAttraction(e) {
    e.preventDefault();
    var example = $(this).children('img').attr('src', $(this).children('img').attr('src').replace('/thumbs', ''));

});

Upvotes: 3

Related Questions