Edgars
Edgars

Reputation: 953

Change image without page refresh or reload

I am using this guide.

http://jsfiddle.net/nz8qy41y/

Problem: When I click on [1] [2] or [3] main image is not changing. Instead I am redirected to image.

View. Main image:

<div class="block-2-image"> 

<a href=<%[email protected](:original)%> data-lightbox="gallery"><%=  image_tag @advertisement.pictures.first.image.url(:medium),
    :title=> @advertisement.name,:id=>"main-image", :alt =>                                   @advertisement.name%></a>

</div>

Thumbnail images:

<ul class="thumbnail">
    <% @advertisement.pictures.to_enum.with_index(1) do |thumb, index|%>


         <li><a href=<%=thumb.image.url(:medium)%>><%= index %></a></li>


    <% end %> 
</ul>

Script:

$(document).ready(function(){
   $('.thumbnail li').on('click',function(){
      $('.block-2-image a').find('img').attr('src', $(this).attr('src'));
   });
});

Now when I click on small images it links to right image, but in other view. I need to change image in the same view.

Any help ?

Thanks.

Upvotes: 0

Views: 1554

Answers (3)

Edgars
Edgars

Reputation: 953

It was my mistake.

I had duplicate script code inside Application.js that mixed up everything.

Upvotes: 0

eatonphil
eatonphil

Reputation: 13672

Pure JS variation of @Mohamed's answer (not tested):

window.onload = function() {
    var selector = document.querySelector(".thumbnail li img");
    selector.addEventListener("click", function() {
        var img = document.querySelector(".block-2-image img");
        img.setAttribute("src", selector.getAttribute("src"));
    });
}

Upvotes: 1

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

include jquery if it not included in jquery

$(document).ready(function(){
   $('.thumbnail li img').on('click',function(){
      $('.block-2-image').find('img').attr('src', $(this).attr('src'));
   });
});

but with that way its better to type a full path for your images in html

Upvotes: 1

Related Questions