Why isn't the class added/removed? - Javascript [duplicate] - javascript

This question already has answers here:
javascript onclick happening on page load
(5 answers)
Closed 5 months ago.
I am trying to create a link, which looks and feels like an <a> tag item, but runs a function instead of using the href.
When I try to apply the onclick function to the link it immediately calls the function regardless of the fact that the link was never clicked. Any attempt to click the link thereafter fails.
What am I doing wrong?
HTML
<div id="parent">
Send
</div>
Javascript
startFunction();
function secondFunction(){
window.alert("Already called!?");
}
function startFunction() {
var sentNode = document.createElement('a');
sentNode.setAttribute('href', "#");
sentNode.setAttribute('onclick', secondFunction());
//sentNode.onclick = secondFunction();
sentNode.innerHTML = "Sent Items";
//Add new element to parent
var parentNode = document.getElementById('parent');
var childNode = document.getElementById('sendNode');
parentNode.insertBefore(sentNode, childNode);
}
JsFiddle
As you can see I tried two different ways of adding this onclick function, both of which have the same effect.

You want .onclick = secondFunction
NOT .onclick = secondFunction()
The latter calls (executes) secondFunction whereas the former passes a reference to the secondFunction to be called upon the onclick event
function start() {
var a = document.createElement("a");
a.setAttribute("href", "#");
a.onclick = secondFunction;
a.appendChild(document.createTextNode("click me"));
document.body.appendChild(a);
}
function secondFunction() {
window.alert("hello!");
}
start();
You could also use elem#addEventListener
a.addEventListener("click", secondFunction);
// OR
a.addEventListener("click", function(event) {
secondFunction();
event.preventDefault();
});

Related

Modal popup window with Javascript

I have a clickable image that when you click a modal popup appears. I want to make sure you can only click it once and while the popup is showing, the clickable image is unclickable. I've tried several methods but no solution works as I want it to.
Here is the code:
init: function () {
var myButton = document.getElementById("kaffePic");
var clickable = true;
console.log(clickable);
myButton.onclick = function(e) {
e.preventDefault();
console.log(clickable);
if(clickable)
{
clickable = false;
popup(myButton, clickable);
}
else
{
return false;
}
};
}
And here is a part of the popup window (removed some code that has nothing to do with the issue).
function popup(theButton, returnClick) {
var myDiv = document.createElement("div");
myDiv.className = "popupWindow";
var newButton = document.createElement('a');
var image = document.createElement('img');
image.src = 'img/theclosebutton.png';
image.className = "popupImage";
newButton.appendChild(image);
myDiv.appendChild(newButton);
newButton.onclick = function () {
document.body.removeChild(myDiv);
returnClick = true;
};
}
Right now I can click it once, and then never again.
Any suggestions?
it's called only once because clickable is set to false after the first click. i suspect you are trying to set it to true in your popup-method by calling returnClick = true; but all that does is setting your argument-value, not the actual clickable-variable itself.
right now, clickable is a variable in the scope of init, so popup can't access it. you could, for example, make clickable a var in the scope of init's parent object. then in popup, you'd access clickable by parentObject.clickable.
//illustration of my example
parentObject {
var clickable,
function init()
}
function popup() {
...
parentObject.clickable = true;
}
Check .one() event handler attachment of jquery and this the .one() of jquery is used to Attach a handler to an event for the elements. The handler is executed at most once per element per event type. second one is link to an stack overflow questions about resetting the .one().Hope this helps

Adding event listeners with Javascript DOM

I'm having trouble adding eventListener to through javascript. Ok, I have a function that creates 4 anchor elements. I want to add an event to them onmouseover that calls a function to change their backkground color. Here's the code (look at the next to last line of createAnchor() to find the relevant code line.
function createAanchor(index) {
var a = document.createElement("a");
var text = getText(index);
var a = document.createElement("a");
var t = document.createTextNode(text);
a.href = getHref(index);
a.appendChild(t);
a.style.textAlign = "center";
a.style.fontSize = "1.2em";
a.style.color = "white";
a.style.fontFamily = "arial";
a.style.fontWeight = "bold";
a.style.textDecoration = "none";
a.style.lineHeight = "238px";
a.style.width = "238px";
a.style.margin = "5px";
a.style.background = eightColors(index);
a.style.position = "absolute";
a.addEventListener("onmouseover", changeColor());
return a;
}
function changeColor() {
alert("EVENT WORKING");
}
Ok here's the problem. When the function gets to a.addEventListener("onmouseover", changeColor()); the function changeColors() executes, but it does not execute later on onmouseover Why is this?
There is no such event onmouseover, the event is called mouseover.
You have to pass a function reference to addEventlistener. () calls the function, as you already noticed, so... don't call it.
This is how it should be:
a.addEventListener("mouseover", changeColor);
I recommend to read the excellent articles about event handling on quirksmode.org.
It's because you wrote changeColors() instead of just changeColors. The () tell JavaScript to call the function.
In other words, changeColors by itself is a reference to the function, while changeColors() refers to the function and then calls it. The result of the function call (the return value from the function) is what's ultimately passed to addEventListener().
Ok I think we need to understand when to use the prefix "on" with the event type. In IE 8 or less then IE8 we use attachEvent and detachEvent which are equivalent to addEventListener and removeEventListener. There are some differences which are not required for this question.
While using attachEvent the event type is prefixed with "on" but in addEventListener no prefix is used.
hence,
elem.attachEvent("onclick",listener); // <= IE8
elem.addEventListener("click",listener,[,useCapture]); // other browsers
I've needed to do something like that too. I have an infoWindow in my map and I need to handle a click event on paragraph in that infoWindow. So I did it like this:
google.maps.event.addListener(infoWindow, 'domready', function()
{
paragraph = document.getElementById("idOfThatParagraph");
paragraph.addEventListener("click", function()
{
//actions that I need to do
});
});
It works for me. So I hope it will help someone :)

Calling JavaScript functions from HTML

How do I execute a JS object's function property from an HTML link?
I have the following JS:
function Tester(elem) {
this.elem = document.getElementById(elem);
}
Tester.prototype.show = function() {
this.elem.innerHTML = 'test';
};
Tester.prototype.test = function() {
alert("a");
};
​
Here is the HTML:
<script type="text/javascript">
var test = new Tester("test");
test.show();
</script>
When I click on the link that gets rendered, it cannot identify the test() function. How would I get it so when a user clicks on the link, the test() function is executed?
The proper way would be to create a DOM element and attach the event handler with JavaScript:
Tester.prototype.show = function() {
var a = document.createElement('a'),
self = this; // assign this to a variable we can access in the
// event handler
a.href = '#';
a.innerHTML = 'test';
a.onclick = function() {
self.test();
return false; // to prevent the browser following the link
};
this.elem.appendChild(a);
};
Since the event handler forms a closure, it has access to the variables defined in the outer function (Tester.prototype.show). Note that inside the event handler, this does not refer to your instance, but to the element the handler is bound to (in this case a). MDN has a good description of this.
quirksmode.org has some great articles about event handling, the various ways you can bind event handlers, their advantages and disadvantages, differences in browsers and how this behaves in event handlers.
It's also certainly helpful to make yourself familiar with the DOM interface.

dynamic link making and pure javascript

I have a link like:
test
and a javascript variable:
var t='this';
How can I make the click on the link go to http://www.example.com/'+this using pure javascript?
(so clicking makes a dynamic url that has the variable t at the end)
You could provide your anchor an id:
test
and then:
var t = 'this';
document.getElementById('mylink').onclick = function() {
window.location.href = this.href + t;
return false;
};
obviously if you are putting this script in the <head> section you might need to wait for the DOM to be ready before attempting to attach click handlers:
window.onload = function() {
document.getElementById('mylink').onclick = function() {
window.location.href = this.href + t;
return false;
};
};
If you cannot modify your DOM to provide an unique id to your anchor you could use the document.getElementsByTagName method which will return you an array of all elements with the given tag in your DOM and then you will have to loop through them and attach the onclick handler to your anchor. In order to identify it between all the links that you might have, you will have to use either its innerHTML text or the current href property.
Based on Darin solition, this opens into a new window and does not modify original;
window.onload = function() {
document.getElementById('mylink').onclick = function() {
window.open(this.href + t);
return false;
};
};

Problem using loop values in function

Beginners Javascript question here.
I am trying to create a function that finds all the links in a given div and sets up an onclick event for each one. I can get the link hrefs correctly, but when I try using them in the onclick function, Javascript seems to only use the last value found:
I.E
I have these links
#purpose
#future
#faq
When I use the onclick function, every link is reported as the #faq link.
Here's the code:
function prepareLinks () {
var nav = document.getElementById('navigation');
var links = nav.getElementsByTagName ('a');
for (var i = 0; i<links.length; i++) {
var linkRef = links[i].getAttribute('href').split("#")[1];
links[i].onclick = function () {
var popUp = "You clicked the " +linkRef +" link";
alert (popUp);
}
}
}
Here you have a closure creation. External variable linkRef becomes saved in inner onclick function. Try this way:
clickFunction() {
var popUp = "You clicked the " + this.href.split("#")[1] +" link";
// this should mean current clicked element
alert (popUp);
}
for (var i = 0; i<links.length; i++) {
links[i].onclick = clickFunction;
}
This is a scoping problem. The expression "You clicked the " +linkRef +" link" is evaluated when the onclick event fires, but what is the value of linkRef at this point?
You're trying to attach a separate onClick handler to each link, but you're accidentally attaching the same one.
You could generate a new function each time by using the new Function() constructor as
links[i].onclick = new Function("","alert('You clicked the '"+linkRef+"' link');");
See http://tadhg.com/wp/2006/12/12/using-new-function-in-javascript/ for more details.
But it's generally better to see if you can have a single handler. It's interesting that when you get to an event handler, the "this" keyword refers to the generator of the event. So you could have your original code refer to this.getAttribute("href"). Too many handlers will make your javascript event processing slow.

Categories