Can't bind click event to a class set of elements - javascript

I've got an image modal that will work when I bind an event handler to an Id, but not when I apply it to a class to have it fire off of any image clicked.
Here is a portion of the html
<div class="column">
<img src="images/journalism-images/j1.jpg" class="grid-img" id="myImage">
<img src="images/journalism-images/j2.jpg" class="grid-img">
</div>
Here is my Javascript below
var modal = document.getElementById('myModal');
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var images = document.getElementById("myImage");
var close = document.querySelector(".image-modal-close");
function changeImage() {
img.src = modalImg.src;
}
images.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
changeImage();
}
so basically what is happening is whatever image I put the ID of #myImage on will fire the modal with the correct image src, but I can't fire the modal when I use something like-
document.querySelectorAll(".grid-img");
can anyone help me out?

var images = document.querySelectorAll(".grid-img");
for ( var index = 0; index < images.length; index ++ ) {
images[index].addEventListener("click",function(e) {
// Do whatever you need.
},false);
}
Or
var $images = $( '.grid-img' );
$images.on( 'click', function(e) {
// Do whatever you need.
});
Remember that querySelectorAll returns set of elements.

Use jquery for this:
$(".grid-img").on("click", function() {
//logic
}
QuerySelectorAll will return a set of elements.
If you want javascript:
document.getElementsByClassName("grid-img").addEventListener("click",function(e) {
//Your logic
}
You can also watch the Example of getElementsByClassName
Example of getElementsByClassBame:
var element = document.getElementsByClassName("grid-img");
element[0].addEventListener("click",function(e) {
//Your logic
}
element[1].addEventListener("click",function(e) {
//Your logic
}

Related

Add onclick event to an HMTL element (img) with JavaScript

I have a js function which creates an img tag and appends it to a div tag:
function createImg() {
let image = document.createElement("img");
image.src = "random.png";
document.querySelector("div").appendChild(image);
I want to add to this img an onclick event, so that when I click on it another function will run. How can I do that? I already searched something on stack and found .addEventListener() & .onclick() but both seem to not work.
You can add the event listener to the image like:
image.addEventListener('click', function(){
// do something
})
var x = 0;
function createImg() {
let image = document.createElement("img");
image.src = `random${x}.png`;
image.addEventListener('click', function() {
console.log(this.src)
})
x++;
document.querySelector("div").appendChild(image);
}
<div></div>
<button onclick="createImg()">
button
</button>
Add id attribute first
image.id = "imgDemo";
Then after appending add the event listener like below:
document.getElementById("imgDemo").addEventListener('click', function() {
//function call here
}, false);

How to close a picture after displaying it?

I wrote JavaScript code that displays an image on click for my site. How do I add a way for it to close after users are done?
function picture() {
var a = document.getElementById('QR');
a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
a.style.display = 'block';
}
<img id="QR" src="https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg" style="display:none;" />
<button onclick="picture()">Apoyar</button>
https://jsfiddle.net/dmtakr3w/
To close that image after displaying it, you can remove the node by taking the parent element and invoking .removeChild(node); on the parent element.
function closePicture() {
var a = document.getElementById('QR');
var parent = a.parentNode;
console.log(parent);
parent.removeChild(a);
}
If you assign this function to a button you are able to close the image by clicking it:
<button onclick="closePicture()">Close</button>
You can also do a setTimeout() to automatically close the image after a certain amount of seconds or so:
// Removes the image after 5 seconds upon opening:
function picture() {
var a = document.getElementById('QR');
a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
a.style.display='block';
setTimeout(function() {
var a = document.getElementById('QR');
a.parentNode.removeChild(a);
}, 5000);
}
As Sag1v said in the comments, just add an on click event to the QR code tag and switch the display back to none.
function picture() {
var a = document.getElementById('QR');
a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
a.style.display = 'block';
}
function closePicture() {
var a = document.getElementById('QR');
a.style.display = 'none';
}
<img id="QR" src="https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg" style="display:none;" onclick="closePicture()" />
<button onclick="picture()">Apoyar</button>

Opening Modal from multiple div elements

How can I get all my other .open-img elements to open my modal?
Eventually I want to trigger modals with the image inside, I'm sure I should be using .this, but cant get it to work.
Codepen: http://codepen.io/Middi/pen/EWxKLZ
Javascript
var modal = document.querySelector(".modal");
var modalBg = document.querySelector(".modal-bg");
var closeButton = document.querySelector(".close-button");
var openImg = document.querySelector(".open-img");
closeButton.addEventListener("click", function() {
modal.classList.toggle("closed");
modalBg.classList.toggle("closed");
});
this.openImg.addEventListener("click", function() {
modal.classList.toggle("closed");
modalBg.classList.toggle("closed");
});
Thanks in advance.
You need to insert eventListener on your each open-img element.
for (var i = 0; i < openImg.length; i++) {
openImg[i].addEventListener('click', function(){
modal.classList.toggle("closed");
modalBg.classList.toggle("closed");
})
}
or use ES6 feature Array#from:
Array.from(openImg).forEach(v => v.addEventListener('click', function(){
modal.classList.toggle("closed");
modalBg.classList.toggle("closed");
}));
Codepen link
Here's a solution based on your code. It's not perfect but it should give you a good starting point:
// get all the matching elements
var openImg = document.querySelectorAll(".open-img");
// iterate over them and add the handler for each of them
openImg.forEach(function (image) {
image.addEventListener("click", function() {
// append the image to the modal
document.querySelector('.modal-main').appendChild(image.cloneNode(true))
modal.classList.toggle("closed");
modalBg.classList.toggle("closed");
});
});

To access class attribute using Prototype JS

function Popup() {
}
Popup.prototype.openPopup = function() {
var div = document.getElementById("test");
div.style.display = 'block';
};
Popup.prototype.closePopup = function() {
var div = document.getElementById("test");
div.style.display = 'none';
};
window.onload = function() {
var popup = new Popup();
var opnpopup = document.getElementsByClassName('clck');
opnpopup.addEventListener('click', function() {
popup.openPopup();
});
var cnclpopup = document.getElementById('cancel');
cnclpopup.addEventListener('click', function() {
popup.closePopup();
});
}
HTML code :
<button id="clck" class="clck">click here</button>
<div id="test" class="popup">
This is a test message
<div id="cancel" class="cancel" ></div>
</div>
In above js when i access the class name 'clck' by using document.getElementsByClassName('clck') the popup is not displayed but when we access it through 'id' then it works..So whats the issue please explain
getElementsByClassName returns an array-like object. Check it out here: getElementsByClassName
"Returns an array-like object of all child elements which have all of
the given class names."
opnpopup is an array containing all elements with class clck. You can't bind events on arrays.
window.onload = function() {
var popup = new Popup();
var opnpopup = document.getElementsByClassName('clck');
for ( index = 0; index < opnpopup.length; index++ )
opnpopup[ index ].addEventListener('click', function() {
popup.openPopup();
});
var cnclpopup = document.getElementById('cancel');
cnclpopup.addEventListener('click', function() {
popup.closePopup();
});
}
This code should work, so you bind the click event to all elements in this array.

Copy/Paste element with jQuery

I have a div that I'm appending to another div when a button is clicked. I'm also calling a bunch of functions on the div that gets created.
HTML
<a onClick="drawRect();">Rect</a>
JS
function drawRect(){
var elemRect = document.createElement('div');
elemRect.className = 'elem elemRect';
elemRect.style.position = "absolute";
elemRect.style.background = "#ecf0f1";
elemRect.style.width = "100%";
elemRect.style.height = "100%";
elemRect.style.opacity = "100";
renderUIObject(elemRect);
$('.elemContainer').draggableParent();
$('.elemContainer').resizableParent();
makeDeselectable();
handleDblClick();
}
var createDefaultElement = function() {
..
..
};
var handleDblClick = function() {
..
..
};
var renderUIObject = function(object) {
..
..
};
var makeDeselectable = function() {
..
..
};
I could clone the element when the browser detects a keydown event
$(window).keydown(function(e) {
if (e.keyCode == 77) {
$('.ui-selected').clone();
return false;
}
});
then append it to #canvas. But the problem is, none of the functions I mentioned above get called with this method.
How can I copy/paste an element (by pressing CMD+C then CMD+V) and call those above functions on the cloned element?
The jQuery.clone method returns the cloned node. So you could adjust your code to do something like this:
var myNodes = $('.ui-selected').clone();
myNodes.each(function () {
createDefaultElement(this);
appendResizeHandles(this);
appendOutline(this);
});

Categories

Resources