I was trying to add the functionality of toggleImage in a gallery and checked this thread and the code provided in one of the answers, but got Uncaught TypeError: Cannot read property 'attr' of undefined
in the console.
HTML:
<div id="gallery">
<figure>
<img data-src="/assets/images/small/one.jpg">
<a data-href="/assets/images/one.jpg">
</figure>
<figure>
<img data-src="/assets/images/small/two.jpg">
<a data-href="/assets/images/two.jpg">
</figure>
<figure>
<img data-src="/assets/images/small/three.jpg">
<a data-href="/assets/images/three.jpg">
</figure>
</div>
<div class="modal">
<div class="">
<img class="modal__image" src="">
</div>
<div class="modal__close">X</div>
</div>
JavaScript that works:
import $ from 'jquery'
class ToggleImage {
constructor() {
this.thumbnail = $('#gallery img')
this.modalImage = $('.modal__image')
this.passHref()
}
passHref() {
this.thumbnail.click(e => {
const href = $(e.target).siblings().attr('data-href')
this.modalImage.attr('src', href)
e.preventDefault
return false
})
}
}
const toggleImage = new ToggleImage()
As you can see, var href = $(this)
was changed to $(e.target).siblings()
. Before this change I'd tried to use just this
or just e.target
with getAttribute() and non-arrow function, or add const that = this
before line const href
and use that
instead, but none of them worked. May I know why?
And, so far the click event is bundled with the action code. But because I hope to separate the action from the event, $(e.target) doesn't fit in this case.
class ToggleImage {
constructor() {
this.thumbnail = $('#gallery img')
this.modalImage = $('.modal__image')
this.passHref()
this.event() // added
}
event() {
this.thumbnail.click(this.passHref)
}
passHref() {
// some code other than $(e.target)...
}
}