Adding a function to an element via javascript - 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);
});

Related

How to attach click events to iframe content?

I have a scenario where I wanted to load a page on inital load. I found that this would do the trick:
<main id="mainContent">
<iframe id="InitalIframe" src="./Pages/Start/index.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>
</main>
I have some links in my header which I attach click listners to:
(function() {
document.querySelectorAll(".link").forEach((item) => {
item.addEventListener("click", (event) => {
event.preventDefault();
const url = event.target.dataset["url"];
getHtmlFile(`./Pages/${url}/`, (data) => {
document.getElementById("mainContent").innerHTML = data;
executeScripts();
});
return false;
});
});
})();
This worked untill I added a few links inside of the Start/Index.html file which gets renderd via the iframe.
I have these two buttons inside of that html.
<button type="button" class="link refbtn" data-Url="One">
One
</button>
<button type="button" class="link refbtn" data-Url="Two">
Two
</button>
Since I attached my listners before the iframe has loaded they never get picked up.
But when I waited for the iframe to load:
document.getElementById("InitalIframe").onload = function() {
document.querySelectorAll(".link").forEach((item) => {
item.addEventListener("click", (event) => {
event.preventDefault();
const url = event.target.dataset["url"];
getHtmlFile(`./Pages/${url}/`, (data) => {
document.getElementById("mainContent").innerHTML = data;
executeScripts();
});
return false;
});
});
};
the click events did not get attached and I got a weird looking result on the page.
Question is how do I accomplish this?
For anyone struggling with the same:
I made my life easier by listening for document click events. when I found that an element with a certain class was clicked I triggered desierd functions:
document.addEventListener(
"click",
function(event) {
event.preventDefault();
const classes = event.target.classList;
if (classes.contains("link")) {
const url = event.target.dataset["url"];
app.fetcHtml(`./Pages/${url}/`, (data) => {
document.getElementById("mainContent").innerHTML = data;
});
}
return false;
},
false
);
You can get to work this with a different approach also. In other words, I had the method closest() in pure Javascript finding me the closest event target that is trigerred when I click inside the container. It will always get me the nearest <a> element which I clicked when I had wandered throught the clickable div/container area.
let base; // the container for the variable content
let dataSet;
base = document.getElementById(base.id); // target your Iframe in this case.
base.addEventListener('click', function (event) {
let selector = '.link'; // any css selector for children
// find the closest parent of the event target that
// matches the selector
let closest = event.target.closest(selector);
if (closest !== undefined && base.contains(closest)) {
dataSet= event.target.dataset["url"];
app.fetcHtml(`./Pages/${url}/`, (data) => {
document.getElementById("mainContent").innerHTML = data;
});
}
});
You can try and see if it works like this also.
Cheers

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);

Onclick event not working when creating elements

I was adding elements with this code and the onclick event was working fine:
$("#main").before('<ul class=\"breadcrumb\"><li><span>Home</span></li></ul>');
But I'm not using jQuery anymore, and with the code below, the onclick events are not firing.
Any idea why this is happening?
var breadcrumb = document.createElement('ul');
breadcrumb.className = 'breadcrumb';
var element = document.createElement('li');
var elementlink = document.createElement('a');
elementlink.onclick = function () {
Search("/");
return false;
};
var elementspan = document.createElement('span');
elementspan.innerHTML = 'Home';
elementlink.appendChild(elementspan);
element.appendChild(elementlink);
breadcrumb.appendChild(element);
document.getElementById('main').insertBefore(breadcrumb, null);
Add a listener instead of setting the onclick property of the element.
Apparently it should work though: http://jsfiddle.net/6gb2k/
Try:
elementlink.addEventListener('onclick', function(e) { ... }, false);
or cleaner:
var handleClick = function(e) {
...
}
elementlink.addEventListener('onclick', handleClick, false);
Your above code should work however according to #crush's comment and my fiddle.

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);

Categories

Resources