Javascript - passing a variable to event handler - javascript

Apologies if my problem sounds trivial to JS experts.
I've created an image slider (carousel) and, while loading thumbnails, I'm trying to create a reference to a full-size image, so that when a thumbnail is clicked - the image opens in another div.
The relevant code within window.onload handler is:
for (var i = 0; i < numImages; ++i) {
var image = images[i],
frame = document.createElement('div');
frame.className = 'pictureFrame';
/* some styling skipped */
carousel.insertBefore(frame, image);
frame.appendChild(image);
} /* for */
My first attempt was to add "onclick" at the end of the for loop:
frame.onclick= function () {
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.style.width=200+"px";
largeImage.style.height=200+"px";
var url=largeImage.getAttribute('src');
document.getElementById('slides').style.display = 'block';
document.getElementById("slides").innerHTML="<img src='url' />";
}
However, this may only work with hard-coded ids (e.g. 'largeImage').
Ideally, I need to pass image.src as a parameter but this (frame.onclick= function (image.src)) will not work.
My next thought was to put all logic of getting image.src to a separate function and displaying it with frame.onclick= myFunction;
However, I came over an example:
<input type="button" value="Click me" id="elem">
<script>
elem.onclick = function(event) {
// show event type, element and coordinates of the click
alert(event.type + " at " + event.currentTarget);
alert("Coordinates: " + event.clientX + ":" + event.clientY);
};
</script>
And here it is above me to understand why in this example a handler can accept a parameter.
What would be a correct way of assigning an image to the onclick event? Or is there a better way of turning a thumbnail into href?

While it might not be the best way, you could place the full size image path as a data-attribute on your thumbnail.
<img id="thumbnail" src="thumbnailpath" data-fullSizeImage="fullSizePath">
Then on your onclick, you could access the thumbnail element and get it's data- attribute.
function onClick(event){
var fullSizePath = event.currentTarget.getAttribute("data-fullSizeImage");
//Do whatever you want with fullsizepath
}
Code is untested; but, something like that should work based on my experience.
data attributes are a very flexible custom attribute for developers to use. Essentially you start with "data-" and then append a name to represent the attribute. Here is the documententation link.

You can create a closure (that is, an anonymous function) and register it as an event handler to access variables from outside the event handler inside the event handler itself:
for (var i = 0; i < numImages; ++i) {
/* create element */
element.addEventListener('click', function (event) {
console.log('The index is ' + i);
});
}
However, this will not quite work, since the variable i is changed every time the loop increases it, and closures don't "capture" the current value, only the reference itself, so at the end i will be equal to numImages for each event listener.
If you're using ES6 you can overcome this by using let (or const) to prevent this behavior:
for (let i = 0; i < numImages; ++i) {
/* create element */
element.addEventListener('click', function (event) {
console.log('The index is ' + i);
});
}
If using ES6 is not an option, you can still accomplish this in ES5 and earlier by wrapping the inside of your loop in a function that takes i as a parameter, which makes sure each event handler references different variables, since these parameters are different variables for each iteration:
for (var i = 0; i < numImages; ++i) {
(function (index) {
/* create element */
element.addEventListener('click', function (event) {
console.log('The index is ' + index);
});
})(i); /* pass in i here, which will be assigned to the index parameter */
}

Related

Creating images with Ajax

I'm using a Bootstrap theme and I wanted the image gallery on the theme's image display page to load via AJAX.
Photos come as JSON with AJAX but I couldn't get them to show on the page.
The gallery related part of this theme from the original JS file:
var productGallery = function () {
var gallery = document.querySelectorAll('.product-gallery');
if (gallery.length) {
var _loop8 = function _loop8(i) {
var thumbnails = gallery[i].querySelectorAll('.product-gallery-thumblist-item'),
previews = gallery[i].querySelectorAll('.product-gallery-preview-item');
for (var n = 0; n < thumbnails.length; n++) {
thumbnails[n].addEventListener('click', changePreview);
} // Changer preview function
function changePreview(e) {
e.preventDefault();
for (var _i3 = 0; _i3 < thumbnails.length; _i3++) {
previews[_i3].classList.remove('active');
thumbnails[_i3].classList.remove('active');
}
this.classList.add('active');
gallery[i].querySelector(this.getAttribute('href')).classList.add('active');
}
};
for (var i = 0; i < gallery.length; i++) {
_loop8(i);
}
}
}();
Data from JSON file with Ajax:
some AJAX code..
if (slidePhotos.photos) {
for (let x= 0; x< slidePhotos.photos.length; x++) {
document.getElementById('gallery_photos_div').innerHTML += '<div class="product-gallery-preview-item" id="' + x+ '"><img src="' + slidePhotos.photos[x].url + '" alt=""></div>';
document.getElementById('gallery_thumbs_div').innerHTML += '<a class="product-gallery-thumblist-item" href="#' + x+ '"><img src="' + slidePhotos.photos[x].url + '"></a>';
}
}
The HTML Code is generated but unfortunately the images do not change when I click on it.
Sample JSON:
[
{
"url":"https://example.com/image1.jpg",
"url":"https://example.com/image2.jpg"
}
]
Can you tell me where I made a mistake?
I see a couple of problems here:
It looks like the code that you're using to populate your slideshow with new images from that JSON file appends a div.product-gallery-preview-item to your slideshow container, but doesn't append a corresponding .product-gallery-thumblist-item. In your productGallery function, your click handler is being bound to the latter, not the former. You'll want to make sure those target thumbnail elements are added as well as the preview ones.
Presumably, your productGallery function is fired when the page/DOM is first loaded to initialize the slideshow. The click event handlers that control the functionality of your slideshow are bound only to the elements that are present when the function runs. If you're not running this function repeatedly when appending content via AJAX (I hope you're not, as this would bind duplicate event handlers to the elements already in the slideshow), you'll need to ensure that your new elements are primed to respond to click in the same way that your existing ones are. You have a couple of options here:
Refactor productGallery so that it can be invoked repeatedly with the same slideshow, e.g: adding a :not(.slideshow-processed) to the the end of your .product-gallery-thumblist-item and .product-gallery-preview-item query selectors, and then adding the slideshow-processed class to these elements after binding your event handlers so they won't be processed again during subsequent invocations of productGallery.
Refactor productGallery to use event delegation (where a parent element listens for an event that occurs on one of its child elements). This would allow you to bind your event handler to the .product-gallery container just once, and have it fire for any preview/thumbnail pair that gets appended to the slideshow, without having to re-invoke productGallery. You can read more about event delegation at https://javascript.info/event-delegation.
Hopefully this points you in the right direction. Happy coding!

Jquery using $this in a for loop in an each loop

Here's my code for a basic jquery image slider. The problem is that I want to have many sliders on one page, where each slider has a different number of images. Each slider has the class .portfolio-img-container and each image .portfolio-img.
Basic html setup is as follows:
<div class="portfolio-item"><div class="portfolio-img-container"><img class="portfolio-img"><img class="portfolio-img"></div></div>
<div class="portfolio-item"><div class="portfolio-img-container"><img class="portfolio-img"><img class="portfolio-img"></div></div>
And javascript:
$.each($('.portfolio-img-container'), function(){
var currentIndex = 0,
images = $(this).children('.portfolio-img'),
imageAmt = images.length;
function cycleImages() {
var image = $(this).children('.portfolio-img').eq(currentIndex);
images.hide();
image.css('display','block');
}
images.click( function() {
currentIndex += 1;
if ( currentIndex > imageAmt -1 ) {
currentIndex = 0;
}
cycleImages();
});
});
My problem comes up in the function cycleImages(). I'm calling this function on a click on any image. However, it's not working: the image gets hidden, but "display: block" isn't applied to any image. I've deduced through using devtools that my problem is with $(this). The variable image keeps coming up undefined. If I change $(this) to simply $('.portfolio-img'), it selects every .portfolio-img in every .portfolio-img-container, which is not what I want. Can anyone suggest a way to select only the portfolio-imgs in the current .portfolio-img-container?
Thanks!
this within cycleImages is the global object (I'm assuming you're not using strict mode) because of the way you've called it.
Probably best to wrap this once, remember it to a variable, and use that, since cycleImages will close over it:
$.each($('.portfolio-img-container'), function() {
var $this = $(this); // ***
var currentIndex = 0,
images = $this.children('.portfolio-img'), // ***
imageAmt = images.length;
function cycleImages() {
var image = $this.children('.portfolio-img').eq(currentIndex); // ***
images.hide();
image.css('display', 'block');
}
images.click(function() {
currentIndex += 1;
if (currentIndex > imageAmt - 1) {
currentIndex = 0;
}
cycleImages();
});
});
Side note:
$.each($('.portfolio-img-container'), function() { /* ... */ });
can more simply and idiomatically be written:
$('.portfolio-img-container').each(function() { /* ... */ });
Side note 2:
In ES2015 and above (which you can use with transpiling today), you could use an arrow function, since arrow functions close over this just like other functions close over variables.
You can't just refer to this inside of an inner function (see this answer for a lot more detailed explanations):
var self = this; // put alias of `this` outside function
function cycleImages() {
// refer to this alias instead inside the function
var image = $(self).children('.portfolio-img').eq(currentIndex);
images.hide();
image.css('display','block');
}

Event target should be anchor but is image instead

I am working on a dialog script in Vanilla JS. I ran into a problem with the click event on the video image. Even tough the image is surrounded with an anchor tag it shows the image as the event.target on the "trigger-dialog-open" event.
Here is the HMTL:
<a class="trigger-dialog--open thumbnail" data-dialog-id="dialog-video" href="javascript:;">
<figure>
<img src="http://i.ytimg.com/vi/id/sddefault.jpg" alt="" />
</figure>
</a>
And this is the event in JS:
var openTriggers = document.getElementsByClassName('trigger-dialog--open');
for (var i = 0; i < openTriggers.length; i++) {
openTriggers[i].addEventListener("click", function (event) {
this.openDialog(event.target.getAttribute('data-dialog-id'));
}.bind(this), false);
}
The event handler wants to know the dialog-id from the anchors data attribute. It can't be found because it thinks the image is the event.target, not the actual anchor. How can I correct this? Thanks!
Use event.currentTarget. The event.target is supposed to be the img element since that is what the user has clicked on. The click then bubbles up through the image's containers. event.currentTarget gives you the element that the click handler was actually bound to.
(Or if you didn't bind this to some other object you could use this within the click handler and it should also be the current target.)
I have a few questions is the var openTriggers supposed to be a part of a module hash? Because if it's global then you don't use a this, you only add a this, if it's referencing a variable that the function is also contained in. For example:
var aThing = {
openTriggers: document.getElementsByClassName('trigger-dialog--open'),
openModal: null,
openDialog: function(clickedThingAttr){
if(this.openModal !== null){
this.openModal.style.display = 'none';
}else{
this.openModal = document.getElementById(clickedThingAttr);
}
this.openModal = document.getElementById(clickedThingAttr);
this.openModal.style.display = 'block';
},
setEventListenersNStuff: function(){
for (var i = 0, n = this.openTriggers.length;i < n; i++) {
this.openTriggers[i].addEventListener("click", function (event) {
this.openDialog(event.target.getAttribute('data-dialog-id'));
});
};
}
};//end of aThing hash object
aThing.setEventListenersNStuff();
There are a few issues here:
1. why are you using .bind I think that is a jQuery thing, you want to pass a string to another function when an object is clicked, there no need for binding at all.
2. Also make sure that if you want to do something like open a modal, there is no need to call another method unless it's kinda complex.
3. What about other potential dialogs, it seems that when a .trigger-dialog--open is clicked you're just showing that one one modal with the embedded id, but what about others? Make sure all modals are closed before you open a new one, unless you want to have like 10 modals are open.
A thing to note: I added the line var i = 0, n = openTriggers.length;i < n; i++, now in this case it's silly optimization, and I heard for modern browsers this doesn't apply, but to explain why I added it, is because i < openTriggers.length would count and integrate the array N times. (This may be an outdated optmiziation).
If you meant global
Below I added a different set of code, just in case you meant that var openTriggers is global, kinda like you wrote above. Also I used querySelectorAll for this which is like jQuery's $('.thing') selector.
anyhoo, I also added
var openTriggers = document.querySelectorAll('.trigger-dialog--open');
var n = openTriggers.length;
function openDialog(ddId){
for (var i = 0;i < n; i++) {
openTriggers[i].style.display = 'none';
};
document.getElementById(ddId).style.display = 'block';
};
for (var i = 0;i < n; i++) {
openTriggers[i].addEventListener("click", function (event) {
openDialog(event.target.getAttribute('data-dialog-id'));
});
}
}
So for the question of hiding already open modals I would suggest you could either cache the open Dialog within a module, or you could toggle a class, which would be less efficient since it would require an extra DOM search. Additionally you could add a if this.openModal.id === clickedThingAttr to hide if open, that way you got a toggle feature.
Anyways I suggest you read up on this stuff, if you want to use plain JS but would like the features of jQuery: http://blog.romanliutikov.com/post/63383858003/how-to-forget-about-jquery-and-start-using-native
Thank you for your time.
You can use a closure
var openTriggers = document.getElementsByClassName('trigger-dialog--open');
for (var i = 0; i < this.openTriggers.length; i++) {
(function(element) {
element.addEventListener("click", function (event) {
element.openDialog(event.target.getAttribute('data-dialog-id'));
}, false)
})(openTriggers[i]);
}

Loading an image but onload/onerror not working as expected

I have a div
<div id='cards'>
Which I want to fill with images based on some logic. But only when images are first loaded into memory. Otherwise, through onerror I wanna fill in some text..
function pasteCard(card, to){
if (typeof(card) == 'string')
card = [card];
var image = [];
for (var i = 0; i < card.length; i++) {
image[i] = new Image();
image[i].src = '/sprites/open/' + card[i] + '.png';
image[i].onload = function() {
pasteImage(to, image[i]);
}
image[i].onerror = function() {
pasteText(to, card[i]);
}
// alert(card[i]) #1
}
function pasteImage(to, image) {
to.append(image);
}
function pasteText(to, text) {
// alert(card[i]) #2
to.append(text);
}
}
pasteCard(['ABC123', 'DEF456', 'GHI789'], $('#cards'));
But this isn't working.
Problem/weirdness: If only #2 alert is active it returns nothing. But strangely if #1 alert is also active it does kinda work... (but still doesn't load my images, and mostly fails too when other code is involved)
Question: Why is it not working without #1 alert (at least in that jsfiddle)
suggestions?: what should I do?
Onload and onerror events are fired (executed) outside the scope of your function so your variables will be undefined. In the event method you have access to this which is the image object. You can set a data attribute to each image and access that in your error event.
Here is an example:
http://jsfiddle.net/7CfEu/4/
The callbacks are not in the same scope as your image array is - therefor you need to declare a variable then will "connect the scopes" and use it inside the callbacks
also the i variable probably changes until the callback is fired - so by using it inside the callback you will get undefined behavior
for (var i = 0; i < card.length; i++) {
var current_card = card[i];
var current_image = new Image();
current_image.onload = function() {
pasteImage(to, current_image);
}
current_image.onerror = function() {
pasteText(to, current_card);
}
current_image.src = '/sprites/open/' + current_card + '.png';
image[i] = current_image;
}
Fiddle: http://jsfiddle.net/7CfEu/6/
(Also - closing the div tag is never a bad idea)
Just in case anyone ends up here for same reason I did.
Was going crazy because onload and onerror were not firing in the page I was building. Tried copy pasting
var myimage = new Image();
myimage.onload = function() { alert("Success"); };
myimage.onerror = function() { alert("Fail"); };
myimage.src = "mog.gif" //Doesn't exist.
Which was working within codepen and random otherwise blank pages.
Turns out the problem I was having was that I was doing AJAX requests earlier in the page. This involved authorization which in turn involved a call to
setRequestHeader();
This was resulting in a net::ERR_FILE_NOT_FOUND error instead of the expected GET mog.gif 404 (Not Found)
This seemed to prevent proper triggering of events.
Revert with
xhr.setRequestHeader("Authorization", "");

specific function in Javascript

I have a function took on a tutorial, it works fine with one only element but I want to use it with some elements and I do not know enough about Javascript to do so.
This is my function :
var elements = document.getElementsByClassName('boules');
for (var i = 0; i < elements.length; i++) {
gameAccel(elements[i]);
}
function gameAccel(sphere) {
var x=20,y=300,vx=0,vy=0,ax=0,ay=0;
if(window.DeviceMotionEvent!=undefined){
window.ondevicemotion=function(e){
ax=event.accelerationIncludingGravity.x*3;
ay=event.accelerationIncludingGravity.y*3;
}
monInterval = setInterval(function(){
var landscapeOrientation=window.innerWidth/window.innerHeight>1;
if(landscapeOrientation){
vx=vx+ay;
vy=vy+ax;
}else{
vy=vy-ay;
vx=vx+ax;
}
vx=vx*0.98;
vy=vy*0.98;
y=parseInt(y+vy/50);
x=parseInt(x+vx/50);
boundingBoxCheck();
sphere.style.top=y+"px";
sphere.style.left=x+"px";
},25);
}
function boundingBoxCheck(){
if(x<0){x=0;vx=-vx;}
if(y<0){y=0;vy=-vy;}
if(x>document.documentElement.clientWidth-40){
x=document.documentElement.clientWidth-40;
vx=-vx;
}
if(y>document.documentElement.clientHeight-40){
y=document.documentElement.clientHeight-40;
vy=-vy;
}
}
}
I have one element with "boules" class, it works, if I have several elements with "boules" class it doesn't works.
This function is used on mobile device with gyroscope. (this is the basic example http://www.albertosarullo.com/demos/accelerometer/).
Someone can explain me why and how I can correct that ?
Thanks a lot.
You are overwriting window.ondevicemotion and monInterval every time you call the function. Only the last handler will be triggered. Instead, use addEventListener to attach multiple handlers and a local variable.
You have overwrites window.ondevicemotion handler in every loop. It must works only for last handler.

Categories

Resources