Im using jQuery too. Im trying to call one method keyPressEvent on pressing enter button. Whats wrong in the code
var AplOperations = function() {
// this function i want to call when an enter button is pressed
this.keyPressEvent = function() {
// my code goes here
}
}
var myOpr = new AplOperations();
document.onkeyup = myOpr.keyPressEvent();
You don't need the () after myOpr.keyPressEvent, other wise the function will be executed intermediately.
Working example: (click first on the panel for the focus)
var AplOperations = function() {
// this function i want to call when an enter button is pressed
this.keyPressEvent = function() {
// my code goes here
var elem = document.getElementById("test");
elem.innerHTML += "key pressed<br>"
}
}
var myOpr = new AplOperations();
document.onkeyup = myOpr.keyPressEvent;
<div id="test"></div>
You have to wait for the keyup and execute your things in callback. Right now it executes when the script gets execute.
document.onkeyup = function () {
myOpr.keyPressEvent();
}
Updated Demo
This line is wrong:
document.onkeyup = myOpr.keyPressEvent();
Using brackets immediately calls the function and the result is assigned to the onkeyup handler. If you remove the brackets your function will be assigned as a handler
Related
I am trying to use an event listener for when I click on an object.
My HTML file
<div id="left">
</div>
<div id="right">
</div>
My JavaScript file
function changeImg(which)
{
if(which === "left")
{
alert("left");
}
else
{
alert("right");
}
}
var leftClick = document.getElementById("left");
leftClick.addEventListener("click", changeImg("left"), true);
var rightClick = document.getElementById("right");
rightClick.addEventListener("click", changeImg("right"), false);
Here is my JSFiddle, https://jsfiddle.net/pb4759jh68/zqzdhcnw/1/
My question is, why does my function run as soon as I run the page, rather than waiting until I click on either the left or right div?
Thanks!!!
The problem is with these 2 lines:
leftClick.addEventListener("click", changeImg("left"), true);
rightClick.addEventListener("click", changeImg("right"), false);
The changeImg function is being called immediately, since you are using the parenthesis after the function name. You can do this to prevent it:
var leftClick = document.getElementById("left");
leftClick.addEventListener("click", function() {
changeImg('left');
}, true);
var rightClick = document.getElementById("right");
rightClick.addEventListener("click", function() {
changeImg('right');
}, false);
Here, we pass an anonymous function as a refernce, which will be called by the browser upon the click event. Inside the function, we are calling our own function changeImg.
addEventListener requires a function as second argument. You're currently evaluating the handler function changeImg("left"), and assigning the result as the event handler. Try this instead:
var leftClick = document.getElementById("left");
leftClick.addEventListener("click", function() { return changeImg("left") }, true);
var rightClick = document.getElementById("right");
rightClick.addEventListener("click", function() { return changeImg("right") }, false);
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 ;-)
Hello I have some code in which I take user input through in html and assign it to,two global variables
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
Which next show up in this addeventlistener function as parameters of the whowon function
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
The click event is meant to trigger the whowon function and pass in the parameters
function whowon(FirstScore, SecondScore, FirstTeam, SecondTeam) {
if (FirstScore > SecondScore) {
FirstTeam.win();
SecondTeam.lose();
} else if (FirstScore < SecondScore) {
SecondTeam.win();
} else {
FirstTeam.draw();
SecondTeam.draw();
}
}
However the values are null,as I get a cannot read properties of null error on this line
var spursscoref = document.getElementById("spursscore").value;
I am pretty sure the problem is coming from the addlistener function,any help would be appreciated
Well you could do something like this -
$( document ).ready(function() {
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
});
Wrap your code in $(document).ready(function(){}). This will ensure that all of your DOM elements are loaded prior to executing your Javascript code.
Try putting all of your code inside this
document.addEventListener("DOMContentLoaded", function(event) {
//Your code here
});
My guess is that your code is executed before the html actually finished loading, causing it to return null.
How can I add an eventlistener to my button? When the button is clicked the function speler1gooien has to run. When I run my example code below the function speler1gooien is fired on page load. What is the correct way to run my function only when clicked?
window.onload = function () {
buttonSpeler1 = document.getElementById("buttonspeler1");
buttonSpeler2 = document.getElementById("buttonspeler2");
tafelp2.src = "images/rechts_" + aantalBekersP2 + ".png";
resultaat = document.getElementById("resultaat");
buttonSpeler1.addEventListener("click", speler1gooien());
};
var speler1gooien = function() {
// some code
}
Remove the parenthesis in the call speler1gooien() because it's causing your function to be executed immediately, and the return value is being passed as the click event handler.
buttonSpeler1.addEventListener("click", speler1gooien);
// ^ removed ()
By removing the parenthesis, you are passing the function object, instead of executing it.
You are trying to attach function speler1gooien as onclick handler, but your code attaches as handler the result of spele1gooien function. Just remove () following name of that function
window.onload = function () {
buttonSpeler1 = document.getElementById("buttonspeler1");
buttonSpeler2 = document.getElementById("buttonspeler2");
tafelp2.src = "images/rechts_" + aantalBekersP2 + ".png";
resultaat = document.getElementById("resultaat");
buttonSpeler1.addEventListener("click", speler1gooien);
};
var speler1gooien = function() {
// some code
}
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.