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

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.

Related

Set JS Variable to href of clicked anchor dynamically

I need to set a variable's value based on the href of a clicked link.
I know that I can set the variable using an event listener that would run this when the link is clicked
var x = document.getElementById("myAnchor").href
But that is set to a single element. I need it to work dynamically based on which link is clicked. For example:
Partner A
Partner B
Partner C
// function to attach click event to all links
function attachClickEvent() {
var linklist = document.getElementsByTagName('a');
var listLength = linklist.length;
var i = 0;
for (; i < listLength; i++) {
linklist[i].addEventListener("click", ClickedLinkEvent);
}
}
window.onload = attachClickEvent;
// function that creates click event
function ClickedLinkEvent() {
var anchor = obj.href;
console.log(anchor);
if (anchor.includes('clientdomain')) {
//do nothing
} else {
SendLinkEvent();
}
}
// function to run on click event
function SendLinkEvent() {
ga('send', {
hitType: 'event',
eventCategory: 'Affiliate Link',
eventAction: 'Click',
eventLabel: anchor
});
}
The anchor variable needs to be set to /link1 if Partner A is clicked, but /link2 if Partner B is clicked.
So, is there a way to do this with vanilla JS?
If you adjust the ClickedLinkEvent method declaration and add an argument to the method signature, then you will have the event object. The event object has a target parameter. If I understood you correctly, this is what you need. Don't you?
function ClickedLinkEvent(e) {
console.log('hello', e);
var anchor = e.target.href;
console.log(anchor);
if (anchor.includes('clientdomain')){
//do nothing
}
else {
SendLinkEvent(anchor);
}
}
You can set custom attributes to the a element like this:
Link A
Then in your js file:
var data_partner= document.getElementById('myAnchor').getAttribute('data-partner');

How to assign event handlers to multiple elements (colorPicker)

I'm trying to find a way to assign event handlers to each box that I create dynamically. At the moment the user can click "Add above" or "Add below" and 2 rows of boxes will appear wherever they clicked.
I'm trying to make it so that when the user clicks on a specific square, a colorPicker will pop up and that specific square's color can be changed.
However, my program is a bit buggy, it only works for the first square that the user clicks on and the colorPicker never pops up again.
Does anyone know how I can go about fixing this or if there is a better alternative?
My code:
http://codepen.io/anon/pen/bwBRmw
var theParent = document.querySelector(".container");
theParent.addEventListener("click", doSomething, false)
//var picker = new Picker()
function doSomething(e) {
console.log("gets inside doSomething")
console.log(e.target)
console.log(e.currentTarget)
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
console.log("Hello " + clickedItem);
var k = document.getElementById(clickedItem)
var picker = new Picker(k)
picker.show();
}
picker.on_done = function(colour) {
$(k).css('background-color',colour.rgba().toString());
picker.hide()
}
//e.stopPropagation();
}
I noticed in your CodePen that you didn't post the full code for doSomething. You have a problem because the picker variable is local to the function. If the code execution doesn't land inside the IF-statement, the picker variable is never created. Simply uncomment the code declaring the picker variable outside the function, and remove the var directive from in front of the line of code where you instantiate a new picker. Furthermore, you need to reset the "parent" element of the picker, since there is only one picker on the page: picker.settings.parent = k;
var picker = null; // Initialize global variable
function doSomething(e) {
console.log("gets inside doSomething")
console.log(e.target)
console.log(e.currentTarget)
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
console.log("Hello " + clickedItem);
var k = document.getElementById(clickedItem)
// Reference the global "picker" variable
if (!picker) {
picker = new Picker(k)
} else {
// Set the "parent" element of the picker to the newly clicked element
picker.settings.parent = k;
}
picker.show();
}
picker.on_done = function(colour) {
$(k).css('background-color',colour.rgba().toString());
picker.hide()
}
//e.stopPropagation();
}

Trigger addEventListener on live element that is not in the DOM (native JavaScript)

I'm stuck with my modal popup plugin since a week.
I'll try to explain as much as i can but first, here is the jsfiddle: http://jsfiddle.net/hideo/yth37hhf/27/
I know the code contains some other functions but they are useful for my plugin.
So, my issue is that the function "triggerLinkAction" contains an addEventListener which is not fired.
(function() {
Window.prototype.triggerLinkAction = function(){
var triggeredLink = document.getElementById("triggeredOtherAction");
var inputTarget = document.getElementById("inputText");
console.log('triggeredLink',triggeredLink);
triggeredLink.addEventListener("click", function (e) {
alert('If this pops out, I will be very happy!!!');
e.preventDefault();
inputTarget.value = "This text should be on the input field...";
}, true);
}
})();
The targeted element is inside the modal, and this modal is displayed by clicking on the link "A small modal".
When the plugin calls ShowModal(), I trigger the TransitionEnd event to call a function
[.... code ...]
function ShowModal() {
vars.popupContainer.classList.add("show");
hsdk.PrefixedEvent(vars.popupOverlay, "TransitionEnd", function (e) {
executeFunctions();
});
}
[.... code ...]
The executeFunctions() will check which functions need to be called:
[.... code ...]
function executeFunctions() {
if (vars.opts && vars.opts.fn) {
var allFunctions = vars.opts.fn.split(',');
for (var i = 0; i < allFunctions.length; i++)
{
var functionName = allFunctions[i];
var functionToExecute = window[functionName];
if(typeof functionToExecute === 'function') {
functionToExecute();
}
}
}
}
[.... code ...]
There are some comments on the javascript part about the plugin, but feel free to ask if I can provide any other information.
PS: I don't care about IE for now ;-)

onclick() automatic firing on loading but failing afterwards

I understand that onclick() in html with parenthesis calls automatically. But in my situation, I want to pass a parameter into the onclick function(specifically, the element clicked). So how do I manage this without having onclick fired when the page loads? In addition, the onclick method does not fire after its automatically firing upon loading. My code is below:
for (i = 0; i < returnPostPhotoSrcs().length; i++) {
// var photosArray=returnPhotoNames()
// var imgName=photosArray[i]
var imgSrcArray=returnPostPhotoSrcs();
var imgSrc=imgSrcArray[i]
var postNamesArray=returnPostNamesArray();
var postName=returnPostNamesArray[i]
var img=img_create(imgSrc,postName,'')
img.style.width=returnPostHeight();
img.style.height=returnPostWidth();
img.className="postImage";
img.onmousedown=playShout(img);
var postNamesArray=returnPostNames();
var innerSpan = document.createElement('span');
innerSpan.onmousedown=playShout(innerSpan); //problem line
var text = postNamesArray[i];
innerSpan.innerHTML = text; // clear existing, dont actually know what this does
var outerSpan = document.createElement('span');
outerSpan.className="text-content";
outerSpan.onmousedown=playShout(outerSpan); //another problem line, also doesnt call onclick
var li = document.createElement('li');
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(img)
outerSpan.appendChild(innerSpan)
li.appendChild(imgSpacer)
imgSpacer.style.opacity="0"
// if (i>0 && i<returnPostPhotoSrcs().length-1) {
// hackey
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(imgSpacer)
li.appendChild(outerSpan)
imgSpacer.style.opacity="0"
// }
var outerDiv = document.getElementById("postDivOuter");
outerDiv.appendChild(li)
}
Adding onto this you could also do:
img.onmousedown= function(e) { playShout(e) };
//for playshout
playshout = function(e) {
var element = e.target; //this contains the element that was clicked
};
The function fires because you are calling it. You need to use a closure
img.onmousedown= function() { playShout(img) };
As others have shown, you can create an anonymous function, or another option is to use .bind():
innerSpan.onmousedown = playShout.bind(null, innerSpan);

addEventListener isn't working properly

I want to move some elements between two div's. Everything works normal with onclick event, but when i swicth to addEventListener it lets me switch just a few times the elements.
Here is a previev http://jsfiddle.net/2u6nyxp4/1/ .
Can someone explain why is that ? Thank you.
HTML
<div id="one">
<span>One</span>
<span>Two</span>
</div>
<div id="two"><span>One</span></div>
JAVASCRIPT
var one = document.getElementById('one');
var two = document.getElementById('two');
var movetoOne = function () {
one.appendChild(this);
bindEvents (this,movetoTwo);
}
var movetoTwo = function () {
two.appendChild(this);
bindEvents (this,movetoOne);
}
var bindEvents = function (childList, moveEvent) {
childList.onclick = moveEvent;
}
for (i=0; i < one.children.length ; i+=1 ) {
bindEvents(one.children[i], movetoTwo);
}
for (i=0; i < two.children.length ; i+=1 ) {
bindEvents(two.children[i], movetoOne);
}
If you use oncklick there is only one event-handler for the event at a time. Each time you call bindEvents the old one becomes overwritten by the new one.
If you use addEventListener, each time you call bindEvents a new handler is added to the existing. After ten clicks there are five handlers movetoOne and five movetoTwo attached to the same element and the browser is totally confused.
The way out: remove the existing handler before adding a new one like so:
var bindEvents = function (childList, moveEvent) {
var old = movetoOne;
if (old === moveEvent) old = movetoTwo;
childList.removeEventListener('click', old);
childList.addEventListener('click', moveEvent);
}
Working DEMO here. - - - Reference: removeEventListener().

Categories

Resources