Search code examples
phpjavascripthref

Replacing href text with something else using Javascript


How can I replace the "echo ucwords($row2[mainImage1]);" in the href attribute of the tag below with the "echo $row2[selectionThumb3];" from the src attribute of the tag below using Javascript?

Here is how my code looks:

    <img class="thumbNotSelected" src="../images/ThumbSelection/<?php echo $row2[selectionThumb3]; ?>.jpg"  />

<div class="mainImage magnify">
     <a href="../images/MainImage/<?php echo ucwords($row2[mainImage1]); ?>.jpg" rel="lightbox" title="<?=$row2[name]?>">
           <img class="mainImage small" src="../images/MainImage/<?php echo $row2[mainImage1]; ?>.jpg" /></a>
</div>

Adding my current Javascript:

$('#thumbs').delegate('img', {
click: function(){
$('.mainImage').attr('src',$(this).attr('src').replace('ThumbSelection','MainImage').replace('selectionThumb','mainImage')); //here I replace the src of the Main Image to match the selected thumbnail.
var $this = $(this),
  index = $this.index();
$("#thumbs img").removeClass('thumbSelected');
 $this.addClass('thumbSelected');

}});

There are several thumbs that the user can click on. The main image loads the corresponding picture after clicking on its Thumb. However, the (used for a lightbox) never changes to adapt to the new loaded picture and the lightbox always uses the same image instead of the one the user has clicked on. Thanks!


Solution

  • With the js below you would be dynamically changing the href of your link to the same exact path of the image loaded. Let me know if it works

     $('#thumbs').delegate('img', {
        click: function(){
            $('.mainImage').attr('src',$(this).attr('src').replace('ThumbSelection','MainImage').replace('selectionThumb','mainImage'));
            $('.mainImage a').attr('href',$(this).attr('src').replace('ThumbSelection','MainImage').replace('selectionThumb','mainImage'));
            var $this = $(this),
            index = $this.index();
            $("#thumbs img").removeClass('thumbSelected');
            $this.addClass('thumbSelected');
    
        }});