Add onclick event to an HMTL element (img) with JavaScript - 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);

Related

Adding a function to an element via javascript

So I have a loop that initializes elements and attributes from an array, and I've managed to add everything I need except one thing, a function. The loop in question is below:
for (const character of result) {
let image = document.createElement("img");
image.src = character.src;
image.setAttribute('data-jval', character.jval);
image.setAttribute('id', character.id);
image.setAttribute('class', character.class)
image.setAttribute('draggable', 'true')
// the below function isn't being added to the divs
image.addEventListener('ondragstart', function(event){
let data = event.target.dataset.jval;
event.dataTransfer.setData("text", data);
})
let wrapper = document.createElement('div');
wrapper.appendChild(image);
section.appendChild(wrapper);
}
and the function I'm trying to add to my elements is:
function drag(event) {
let data = event.target.dataset.jval;
event.dataTransfer.setData("text", data);
}
Before trying to create the elements in JavaScript I had them in HTML, and they looked like this:
<img data-jval="a" id="jval-a" src="./images/あ.png" class="j-char-img" draggable="true" ondragstart="drag(event)"/>
but when I recreate it with my loop it looks like this, missing the ondragstart="drag(event"
<img src="/images/あ.png" data-jval="i" id="jval-i" class="j-char-img" draggable="true">
If the rest of my code would be useful I can post that as well.
Just "dragstart" instead of "ondragstart" event:
for (const character of result) {
let image = document.createElement("img");
image.src = character.src;
image.setAttribute('data-jval', character.jval);
image.setAttribute('id', character.id);
image.setAttribute('class', character.class)
image.setAttribute('draggable', 'true')
// the below function isn't being added to the divs
image.addEventListener('dragstart', drag);
let wrapper = document.createElement('div');
wrapper.appendChild(image);
section.appendChild(wrapper);
}
function drag(event) {
let data = event.target.dataset.jval;
event.dataTransfer.setData("text", data);
}
So basically you add the prefix on before the event when you write inline event handlers, just like before when you put your event handler inside your img tag. Same thing for any other events:
click => onclick
submit => onsubmit
keydown => onkeydown
#try to add Semicolon;
image.setAttribute('class', character.class);
image.setAttribute('draggable', 'true');
// the below function isn't being added to the divs
image.addEventListener('ondragstart', function(event){
let data = event.target.dataset.jval;
event.dataTransfer.setData("text", data);
});

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

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
}

How to add onclick event to exist element by Javascript? (document.getElementbyID)

I have a button in my project that when you click over it a function call and add onclick event to all certain elements in my project and show my hidden popup element container.
I have a function that search all exist element in my page and add onclick event to some of elements that they have certain class.
My element is stored in a list array. in each cell of this array (array name is list) stored an element like below:
list[0] = document.getElementById("my_div_id");
list[1] = document.getElementById("my_div_id_1");
list[2] = document.getElementById("my_div_id_2");
...
list[n] = document.getElementById("my_div_id_n");
and I have a function like below in top of my Javascript code:
function say_hello(e, msg) {
if (e == null) e = window.event;
//now e handler mouse event in all browser !!!
alert (e + "::" + msg);
}
I have a function to add onclick event to each element in array. I add onclick event in type of below (separated with (*) comment) but doesn't work any of them:
function search_and_add_events_to_all_dragable_elements (list) {
for (var z = 0; z < list.length; z++) {
list[z].href = "javascript:;";
var e;
var test_msg = "VAYYYYYYYYYY";
/**************
element.onclick = new Function { alert ('hi'); };
element.onclick = new Function () { alert ('hi'); };
element.onclick = new function { alert ('hi'); };
element.onclick = new function () { alert ('hi'); };
element.onclick = new function () { return alert ('hi'); };
element.onclick = function () { return alert ('hi'); };
element.onclick = alert ('hi');
element.onclick = "alert ('hi');";
element.onclick = say_hello(e, test_msg);
element.onclick = "say_hello();";
element.onclick = (function (e, test_msg) { return function(e) { sib(e, test_msg); };
element.onclick = (function () { return function() { alert("ahaaay"); };
**************/
list[z].style["padding"] = "20px";
list[z].style["border"] = "solid 10px";
list[z].style["backgroundColor"] = "#CCC";
}
}
I change style in end of my code to perform my code is work and end truly. style change every time but onclick event doesn't add to my div.
only one way add onclick to my project. that is same as below:
list[z].setAttribute("onclick", "alert(\"hi\");");
but are there better ways?
There is a better way. My first mistake was using JavaScript before my all element load on my page. to solve it you must call element in end of page load or put your javascript code in end of your project. then your code execute exactly when your elements are exist in your page.
for more details about it see links below:
JavaScript that executes after page load
http://www.w3schools.com/jsref/event_onload.asp
My second mistake was hurt :(
I has a div that hold all of my other elements in itself. it was styled display: none; on load. when I call my function it was displayed none and all thins work well (like my new styling) but onclick event didn't work :(( and I spent two days to solve this :((
only be careful your element should not be display: none styled when you are adding your onclick event to it.
then you can use this type of creation onclick event dynamically to your project:
list[z].onclick = (function (e, test_msg) {
return function(e) {
sib(e, test_msg);
};
})(e, test_msg);
this is best way that I know. you can manage event handler and send your arguments also to your function.
I use several time another way of dynamically add onclick event in my project.

How do I declare event object with onclick event using Javascript (not html)?

Here is my code:
function testimage() {
var image;
image = new Image();
with (image) {
id = "page1";
border = 0;
name = "IllustGIF";
useMap = "#MAP1";
src = "sample.gif" + "?d=" + new Date();
// The event argument here is invalid; it's to show what is the desired result.
onclick = function() { RecordMouseClick(event, this.id); };
}
// attached to body tag
document.getElementById("body_ID").appendChild(image);
}
function RecordMouseClick(event, id) {
alert("id: " + id + ", and event object should contain mouse x- and y- coordinates clicked");
}
I need to define the onclick event in JavaScript, not HTML. Now in HTML, it's easy -- just pass event as an argument to the function and, voila, event object in JavaScript But doing it all from scratch, all in JavaScript, without HTML, is challenging for me. When the reference function is called, it's supposed to record the element id and the mouse click x- and y- coordinates from the onclick event.
How can I pass an event to the onclick, such that the event object is valid at run-time?
Thank you.
Here's a sample fiddle.
image.onclick = function(e) {
e = e || window.event;
RecordMouseClick(e, image.id);
};
document.getElementById('id-of-the-html-element').onclick = function(){
// your code
};
or
function doSth(){
// your code
}
document.getElementById('id-of-the-html-element').onclick = doSth;
Read more about it over here: https://developer.mozilla.org/en/DOM/event
Try addEventListener().
image.addEventListener('click',
function(e) {
RecordMouseClick(e, this.id);
}, false);

How to Hide an Image, if not clicked, in N seconds?

I have a button that when is clicked, an image is created using javascript and get prepended to a div (adds it inside a div).
var image = new Image();
var imageHtml = image.toHtml();
$('div.board').prepend(imageHtml);
function Image()
{
this.toHtml = function ()
{
return '<img src=\"myImage.png\" width=\"40px\" height=\"40px\" />';
}
}
This image can be clicked in 2 seconds then user will have 1 more score and if not clicked in that time, then the image should disappear.
How to do that in javascript?
Thanks,
function start_game(image){
var timeout = null;
image.onclick = function(){
clearTimeout(timeout);
//addScore();
};
timeout = setTimeout(function(){
image.onclick = null;
image.style.display = "none";
// remove the image from dom if needed;
}, 2000);
}
Demo: http://jsfiddle.net/UpNCb/
see this, just difference is you going to hide instead of link display
or
give id 'img_id' to your image
function hideimage() {
document.getElementById('img_id').style.display = 'none';
}
setTimeout(hideimage, 10000);
Use the function setTimeout() and the CSS property display or visibility.

Categories

Resources