Kenan Balija
Kenan Balija

Reputation: 703

Changing custom attribute source with jQuery does not update it

Quick Intro: I'm using jQuery.elevateZoom-3.0.8 as to show zoomed picture.

  1. SRC attribute is path to smaller/normal image

  2. DATA-ZOOM-IMAGE attribute is path to bigger image that serves as a zoom.

HTML Code Below:

  <section id="designer-single" class="col-md-7" >
    <div class="magnifier-thumb-wrapper mc">
      <img class="front-magnify"  
      src="../../public/img/burn/purple-front.png"
      data-zoom-image="../../public/img/burn/purple-front-lg.png">
    </div>
 </section>
 <button class='back-image'>Click me</button>

Now I want image to change when user presses a button. Smaller image will change (SRC attribute), but bigger one will not refresh (data-zoom-image attribute) even though i change it with jQuery.

$('.back-image').on('click', function(){
    $('.front-magnify').attr('src', 'public/img/burn/purple-back.png');
    $('.front-magnify').attr('data-zoom-image', 'public/img/burn/purple-back-lg.png');
});

Question is: how do I update state of custom attribute "data-zoom-image" in elevateZoom.js so that it updates on DOM?

https://i.sstatic.net/hFvG7.png => without clicking

https://i.sstatic.net/r0tUw.png => when changing

Example on Codepen: https://codepen.io/kenanbalija/pen/MojOEp

Upvotes: -1

Views: 275

Answers (1)

Daniel Beck
Daniel Beck

Reputation: 21475

What seems likely to be the problem is that you're changing the attribute successfully, but the code in elevateZoom.js is initing based on the original value and isn't watching for changes.

Based on your comment below and a quick look at the plugin source code, my earlier guesses (reinstantiate the plugin by calling .elevateZoom again, or use the responsive option) won't work. This is a one-shot plugin, it's really not designed to be controllable after it's instantiated, so your options are pretty limited.

You could go brute-force and destroy the existing plugin (by removing the whole DOM element) before replacing it with a new one and reinstantiating the plugin.

Or, since you appear to be toggling between two different zoomable images, it may be simpler to instantiate them both separately and hide / reveal each as necessary, something along the lines of

$('.image').on('click', function(){
  $('.front-magnify, .back-magnify').toggleClass('hidden');
})

That'd be a tradeoff between bandwidth and code complexity, of course.

Upvotes: 1

Related Questions