setattribute in javascript - javascript

This is my code to dynamically set the onclick attribute to links, but without me clicking the links itself, the alert is triggered.
window.onload = function() {
var links = document.getElementsByTagName("a");
for(var i=0;i<links.length;i++) {
elm = links[i];
elm.setAttribute("onclick", alert("you clicked a lik"));
}
}

change the corresponding line to:
elm.setAttribute("onclick", function() { alert("you clicked a link");});
If you pass as argument a function call (such as alert('msg')), the function is executed imediatley and the actual passed argument is the function's return value. All you have to do is wrap your eventHandler code into an anonymous function.
Also, you can declare a function that handles your event and send it's name as argument :
function handleClick() { alert("you clicked a link");}
elm.setAttribute("onclick", handleClick);
P.S. : I recommend using the addEventListener functionality instead of plain old onEvent inline attributes :
elm.addEventListener('click', function() { alert("you clicked a link");}, false);

Try to put the alert statement into an anonimous function
window.onload = function()
{
var links = document.getElementsByTagName("a");
for(var i=0; i < links.length; i++)
{
links[i].setAttribute("onclick", function () {
alert("you clicked a link");
});
}
}

Related

How to get value from button after it has been clicked

I'm struggling with this assignment: Pin an event listener to the buttons.
Create a function that gets called when one of the buttons is clicked. Check this with a console.log. Make sure the click event is passed to this function.
Make sure you have access to the value of the button clicked in this function. Check this with console.log. The outcome you want to see in the console when you click is: Leopard / Lion / Elephant / Rhino or Buffalo.
fiveButtons = document.getElementsByClassName("big-five-button");
for (var i = 0; i < fiveButtons.length; i++) {
fiveButtons[i].addEventListener("click", function () {
Array.from(fiveButtons).forEach(function (nameButton) {
console.log(nameButton.innerHTML);
})
});
}
This is what I wrote so far. When I'm clicking the button now, the outcome is the text from all the buttons. While I want the outcome to only be "Lion" after the button lion has been clicked.
<h1>The Big Five</h1>
<ul class="big-five-list">
<li class="big-five-list-item">
<button class="big-five-button">Lion</button>
</li> etc.
when creating an addEventListener you can use the event object to target the element clicked, like this:
fiveButtons[i].addEventListener("click", function (event) {
console.log(event.target.innerHTML);
});
You can change the button to include an onclick function like the below:
https://www.w3schools.com/jsref/event_onclick.asp
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction('Lion')">Lion</button>
<input type="text" value="" id="getValue">
<p id="demo"></p>
<script>
function myFunction(value) {
document.getElementById("getValue").value = value;
}
</script>
</body>
</html>
The onclick function will then have a value inside the () for the function name. This will pass the value you want across to the function and it can be called whatever you want. The above snippet shows an example of how it can be used
Try this solution!
fiveButtons = document.getElementsByClassName("big-five-button");
for (var i = 0; i < fiveButtons.length; i++) {
fiveButtons[i].addEventListener("click", function (item) {
console.log(item.target.innerHTML);
});
}
The function you pass to addEventListener gives an event argument:
fiveButtons = document.getElementsByClassName("big-five-button");
for (var i = 0; i < fiveButtons.length; i++) {
fiveButtons[i].addEventListener("click", function (event) { // use the first argument
console.log('element value:', event.target.value); // log the 'value' of the event target;
// I suspect you want the innerHTML or innerText
console.log('element innerText:', event.target.innerText);
});
}
You can then get the required information from the DOM node in event.target
You don't need the Array.from inside the for loop. You can just do that:
fiveButtons = document.getElementsByClassName("big-five-button");
for (let i = 0; i < fiveButtons.length; i++) {
fiveButtons[i].addEventListener("click", function () {
console.log(fiveButtons[i].innerText);
});
}
EDITED
// Get all the buttons
const fiveButtons = document.getElementsByClassName("big-five-button");
// Iterate through the collection of buttons
// Here is let i = 0 instead of var i = 0, since var has functional scope and let has block scope
// If we used var i = 0 it would not work implicitly because i would exist in the scope of a function,
// and all the event handlers (for each button) would share the same value of i
for (let i = 0; i < fiveButtons.length; i++) {
// For each button register event handler
fiveButtons[i].addEventListener("click", _ => {
// When button is clicked this part of a code is being called
// Because of javascript CLOSURE, it remembers the i value
console.log(fiveButtons[i].innerHTML)
});
}
If this is not understandable please read about closures in javascript.

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

I want to click to implement the event once, then remove event from the element that clicked

As in the title of the question.
I have many elements, because I have used getElementsByTagName('*').
Then, I have added a click event on every element, and I have used loop for that.
See the code:
HTML
<div id="box">
<span class="box"> span</span><br/>
<span class="box">span 2</span><br/>
<span class="box">span 3</span><br/>
</div>
<div id="result"></div>
Javascript
var element = document.getElementsByTagName('*'),
len = element.length, result = document.getElementById('result'), i, timer;
for (i = 0; i < len; i++) {
element[i].addEventListener('click', fn = function (e) {
clearTimeout(timer);
result.style.display = 'inline';
result.innerHTML = "<pre>" + e.target.innerHTML + "</pre>";
timer = window.setTimeout(function () {
result.style.display = 'none';
}, '2000');
e.target.removeEventListener('click', fn);
});
}
I want to when a user clicks on a specific element, implement the
event once, then removes the event from this element only.
Also, I want to add the function(callback) name to the removeEventListener function automatically, not like this e.target.removeEventListener('click', fn) //fn is the callback name.
the event callback gets called with the context of element, you have added the listener to it, here this would point to element[i],so you can change it like:
element[i].addEventListener('click', function fn(e) {
//your stuff
this.removeEventListener('click', fn);
});
note that if you create fn function this way, it is kind of private in the function body, we used to use arguments.callee which is not a good practice these days, you can not use it in strict mode.
all I am saying is by the time strict mode showed up since:
The 5th edition of ECMAScript (ES5) forbids use of arguments.callee()
in strict mode.
we could do that like this:
element[i].addEventListener('click', function(e) {
//your stuff
this.removeEventListener('click', arguments.callee);
});
but the new alternative is using function's label, for instance if you do:
var myfunc = function func(){
//you have access to the current function using func
//and you can add or remove it to/from something
someThing.removeEventListener('click', func);
};
//but if you want to do it here you can have it using myfunc
someOtherThing.removeEventListener('click', myfunc);
So that's what I mean by:
kind of private in the function body
you have access to that function in the function body using its label func, but out there in the code you don't have it.
Define function before as a variable. http://jsfiddle.net/m8UgC/
var element = document.getElementsByTagName('*'),
len = element.length, result = document.getElementById('result'), i, timer;
var fn = function (e) {
clearTimeout(timer);
result.style.display = 'inline';
result.innerHTML = "<pre>" + e.target.innerHTML + "</pre>";
timer = window.setTimeout(function () {
result.style.display = 'none';
}, '2000');
this.removeEventListener('click', fn);
}
for (i = 0; i < len; i++) {
element[i].addEventListener('click', fn);
}

Parse for links that have target="new" and add an onclick event

I have a web site that gets links generated dynamically. I would like to see if I can add an onclick event handler to track external links. I am looking to see links that has target="new" ( which means external to our site) and add the event handler
html code
<a target="new" href="http://twitter.com/cnn">CNN</a>
The code I tried to test is not working. Let me know what is wrong in my code or should I some home append the onclick event to the external links?
Js code
var links = document.getElementsByTagName("a");
for (var i=0; <links.length; i++) {
if(links[i].target == 'new'){
links[i].onclick = function() {
alert("Added onClick: " + links[i].href);
}
}
}
Another answer here is what you should go with (using this) but it's worth addressing the issue of closures in for loops.
If you want to use a variable that changes for each iteration in a for loop in a closure that's created in that for loop, define and call an anonymous function that returns a function to be bound (binded?) to the onclick event.
var links = document.getElementsByTagName("a");
for (var i=0; i<links.length; i++) {
if(links[i].target == 'new'){
links[i].onclick =
function (obj) {
return function(event) {
alert("Added onClick: " + obj.href);
}
}(links[i]);
}
}
Since the parameter (obj) to the anonymous function is passed by value it won't change in subsequent iterations for the for loop. The returned function will have its own copy of the object.
A lot of stuff in Javascript starts making sense when you think of functions as objects that can be passed around.
You can use this in your onclick function and avoid the closure issue
var links = document.getElementsByTagName("a");
for (var i=0; i<links.length; i++) {
if(links[i].target == 'new'){
links[i].onclick = function(){
alert("Added onClick: " + this.href);
}
}
}
are you adverse to jQuery?
$("a[target='new']").click(function(){alert($(this).attr("href"));});

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.

Categories

Resources