I was toying around with trying to get events-on-button-click to work where the JavaScript code triggers some event once a specific button is clicked.
There are no issues when I attempt to do on-click triggers in my project(s), but I just can't seem to get it to work using JSFiddle.
I first followed the tips here: JavaScript not running on jsfiddle.net
Specifically, the part where meder omuraliev writes, "So instead of
<p onclick="lol()" id="foo">
you'd do
var e = document.getElementById('foo');
e.onclick = lol;
in the JS only."
I attempted to follow this instruction which can be seen in the simple example I made here (that doesn't work): https://jsfiddle.net/b7yj3cph/3/
var e = document.getElementById('test');
e.onclick = example;
var example = function( {
alert("hello");
});
<button id='test' type="button" onclick="example()">
<div>
Hello
</div>
I tried other sources and methods but couldn't get any to work. I attempted an example from W3Schools (https://jsfiddle.net/b7yj3cph/) and tried some JSFiddles from searching "jsfiddle button onclick" (https://jsfiddle.net/Dogbyte/62cd0LLq/) which some didn't work.
But some did; like this one (http://jsfiddle.net/lesson8/h4JXs/1/) seems to work fine.
What is uniquely going on that makes the click trigger work for some JSFiddles and not for others? I suspect it has to do with the $(document).ready() part but I've been reading various ways to get this to work and I can't find anything that makes sense to me.
Going back to the Stack Overflow thread that I shared earlier, the top-voted response there had 3 suggestions:
"( easiest, quickest, not ideal ) - change function blah(){} to window.blah = function(){}; making the functions global."
Well, in the JSFiddle posted here that works as expected, there is no use of window. Attempts that I made to use window proved to be fruitless.
"( ideal way ) - use unobtrusive Javascript to attach behaviour to DOM elements from within the JS solely, meaning separate HTML from
JS."
This is a great point and makes sense but still didn't solve my particular
issue.
"Make the jsfiddle not wrap the stuff onload. Change onLoad to no wrap ( body or head )."
My particular example isn't wrapped in onLoad(at least, I don't think that it is). Anyways, thanks!
You have two issues in your fiddle:
Firstly your example function is declared incorrectly:
var e = document.getElementById('test');
e.onclick = example;
var example = function( { // parenthasis should be closed before opening braces
alert("hello");
});
Should be:
var e = document.getElementById('test');
e.onclick = example;
var example = function() {
alert("hello");
}
Secondly, you are declaring the var example below the onclick assignment which is being interpreted as:
e.onclick = undefined
Just move the var example above the e.onclick and fix the syntax issue and it will work:
var e = document.getElementById('test');
var example = function() {
alert("hello");
}
e.onclick = example;
This is the way if you don't want to wait for the DOM to be loaded.
document.getElementById('btnSave').addEventListener('click',() => {
alert('clicked the damn button!');
});
The reason attaching something to .onclick doesn't work is because, for that, you do have to wait for the DOM to load; order of operations is really important in this case.
Related
I was working on some code I wrote and I had this problem where an eventListener I added to a dynamically created element, but it does not "fire" aka work.
var eleButton = document.createElement("button");
eleButton.innerText="Post";
eleButton.type="submit";
...
eleButtonContainer.appendChild(eleButton);
And the eventlistener was a basic "click"
eleButton.addEventListener("click", function() {
console.log("Hello World");
});
That did not work, so i searched around and could not find any answers. I finally found a work around of using document and checking whether or not that element was check or not. So my resulting code became this:
var eleButton = document.createElement("button");
eleButton.innerText="Post";
eleButton.type="submit";
eleButton.id = "usrResponseSubmit";
console.log(eleButton);
document.body.addEventListener('click',function(){
if(event.target.id == "usrResponseSubmit"){
console.log("ok now it works");
}
});
This works fine, but it still makes me question about the code atop. I willing to take the "if it werks it works" route, but I would also still like to use the eleButton.addEventListener route because that was what I always used.
So my two questions are:
is using document.addEventListener bad?
why does eleButton.addEventListner not work?
Before you say, but it works on my end, my code is kinda crap and long. Essentially, I have this eleButton nested in a container that is nested in a container ... (x~10-20). I don't think this is necessarily the problem. But I also have some other eventListeners that "may" overlay with eleButton. I'm not too sure that's the case as i've been trying and testing everything I can.
I have also pulled the eleButton and appended it to an existing object and the event did fire. Can someone give me a run down of when events do not fire?
Nothing is wrong with your code, maybe you just misspelled something. here i made a codepen example you can check.
html:
<div id="btnCon"></div>
...
JS:
const eleButtonContainer = document.querySelector('#btnCon')
var eleButton = document.createElement("button");
eleButton.innerText="Post";
eleButton.type="submit";
eleButtonContainer.appendChild(eleButton);
eleButton.addEventListener("click", function() {
console.log("Hello World");
});
the example on codepen
I have a page with JS functions (which are called on mouse click) within <script> ... </script> tags. While I was testing I had encountered problems with .click method not working many times. Therefore I decided to simply call that function manually. However I found no source on the Internet which taught to do this.
I want to avoid clicking the links and simply call for doSumbit('5').
Thank you!
The JS functions are:
<script language="javascript">
function doSubmit(infoTypeId) {
document.forms[1].INFOTYPEID.value = infoTypeId;
document.forms[1].action = document.forms[1].action + "#" + infoTypeId;
document.forms[1].submit();
document.forms[0].INFOTYPEID.value = infoTypeId;
document.forms[0].submit();
}
function doSubmitOne(infoTypeId) {
document.forms[0].INFOTYPEID.value = infoTypeId;
document.forms[0].submit();
}
</script>
and the on-click links are:
<a href="javascript:doSubmit('11')" >Engine News<br></A>
<a href="javascript:doSubmit('5')" >Parts Identification<br></A>
You can run arbitrary JS with execute_script
page.execute_script("doSubmit('5')")
if you expect a return value use evaluate_script - it's all documented here - http://www.rubydoc.info/gems/capybara/Capybara/Session#evaluate_script-instance_method
Of course if you're actually testing an app, you'd be much better off figuring out why click isn't working for you and fixing that, since by just calling JS functions you're not actually testing that your app works.
EDIT: typo doSubit changed to doSubmit
I've noticed from a few different projects of mine that whenever I click something I add an onClick function to, it always takes two clicks to get them going when a page is freshly loaded. The general structure I use for them is:
function PageChange(){
var welc_p = document.getElementById("welcome");/**gathers page DIVs**/
var page01 = document.getElementById("page01");
var page02 = document.getElementById("page02");
var start = document.getElementById("start_btn");/**gathers buttons**/
var p1_back = document.getElementById("p1_back");
var p1_next = document.getElementById("p1_back");
var p2_back = document.getElementById("p2_back");
var p2_next = document.getElementById("p2_back");
start.onclick=function(){
page01.style.display="block";
welc_p.style.display="none";
window.location="#page01";
};
}/**function**/
then the way I call it in the html is
<div class="some_class" id="start_btn" onClick="PageChange()">!!!LETS GET STARTED!!!</div>
Here's a fiddle of it as well.
https://jsfiddle.net/Optiq/42e3juta/
this is generally how I structure it each time I want to create this functionality. I've seen tons of other posts on here about their items taking 2 clicks to activate but none of them were doing anything near what I was trying to accomplish and it seemed their problem was within their coding. Does anybody know why this is happening?
This is because you are attatching a event handler to your button on click of your button.
This means that one click of the button activates the event handler, not the code within start.onclick=function() {
Then, the second click works becasue the event handler has been activated, and now the code will run.
Try moving your code out of the function, then it will work with just one click
Just had the same issue, and found an easy solution based on the above answer.
Since your function needs two clicks to work, I just called the function above the function and it works fine. This way the function already gets called one time on load, then it gets called the second time when you click it.
yourFunction();
function yourFunction(){
-- content --
}
I also had the same 2 clicks required on intitial interaction and after many searches couldn't find the best solution for my specific nav menu. I tried this solution above but couldn't get it to work.
Stumbled upon this code from a youtube example and it solved my issue. I wanted to nest submenu's for multiple levels and modified it from its original implementation to work best for my responsive mobile menu.
var a;
function toggleFirstLevelMobileSubMenu(){
if(a==1){
document.getElementById("mobile-sub-menu-depth-1").style.display="none";
return a=0;
}
else {
document.getElementById("mobile-sub-menu-depth-1").style.display="flex";
return a=1;
}
}
var b;
function toggleSecondLevelMobileSubMenu(){
if(b==1){
document.getElementById("mobile-sub-menu-depth-2").style.display="none";
return b=0;
}
else {
document.getElementById("mobile-sub-menu-depth-2").style.display="flex";
return b=1;
}
}
Of course, in the CSS I had display: none set for both ID's.
First, the problem:- On first click instead of running js your browser runs the button aka the event.
Solution:- in order to resolve this we need to make sure our function is already before the event is run (this is one of the ways to solve the problem). To achive this we need to load the function aka call the function in some way.
So, i just simply called the function after function is completed.
Code answer-
Just add at the end of your code
PageChange();
I am struggling with onmouseover and onmouseout.
Every site I have been to shows this syntax almost exactly. I practically copied pasted it from Mozilla. The problem I’m having is that it calls the largeDiv and smallDiv functions immediately. (Eventually, I am hoping to apply a new class to the div when during the mouseover event, and return to the old class when mouseout.) I am pretty sure that my mouse events are to blame. I was also wondering if my onload function caused any problems, but when I commented it out, the only thing that changed was the small div did not load, as expected.
I tried to use an event listener, thinking I wasn’t calling the event properly, but that did not work at all, although I am not sure I coded it properly, and didn’t spend more than an hour on the damn thing! I have tried numerous tweaks, camelcasing onmouseover, using parenthesis, etc… Anyway, here is the code:
var introEl = document.getElementById("intro");
//display large div by default and
//use small div with js enabled
window.onload = function(){
introEl.className = "small";
}
function largeDiv(){
console.log("It Worked");
};
function smallDiv(){
console.log("Mouse Out!");
};
introEl.onmouseover = largeDiv();
introEl.onmouseout = smallDiv();
I coded this in my browser and when I copied it to jsFiddle to ask this question it wouldn’t load the small div on load, but it did log the statements. I put it on CodePen and it worked as I have described. Not sure what caused this but this is the second time this has happened.
By the way, if you go to CodePen or jsFiddle, I know my design skills are lacking. I am just doing this for a playground, and for a place to keep code that works, like a notebook. I promise you it will get much much worse.
As always, any help is appreciated.
var introEl = document.getElementById("intro");
//display large div by default and
//use small div with js enabled
window.onload = function(){
introEl.className = "small";
}
function largeDiv(){
console.log("It Worked");
};
function smallDiv(){
console.log("Mouse Out!");
};
introEl.onmouseover = largeDiv; // here you don't need "()" with your defined functions
introEl.onmouseout = smallDiv; // here you don't need "()" with your defined functions
Please go to following fiddle i have made some small changes and its working fine for me
fiddle
Also You could have used
<div id="intro" onmouseover="largeDiv();" onmouseout="smallDiv();">
Mouse over this text
</div>
See working example here fiddle 2
I need to attach a click event on a button tag. I've tried addEventLister, but it still doesn't work.
widget.innerHTML = "<button id=\"w_btn\">do action</button>";
w_btn = document.getElementById("w_btn");
w_btn.addEventListener("click",
function() {
alert("sdf");
}
);
The third optional is required in some browsers.
The following code should work in every decent browser (fiddle: http://jsfiddle.net/5hnPP/2/):
var widget = document.getElementById("widget");
widget.innerHTML = "<button id=\"w_btn\">do action</button>";
var w_btn = document.getElementById("w_btn"); //Added var
w_btn.addEventListener("click",
function() {alert("test")},
false
);
Another possible cause is the existence of another element with ID w_btn, which appears before the #widget element. To solver this, you can adjust your code. Since you overwrite the contents of the #widget element, the first and only content is the button. Define:
var w_btn = widget.firstChild;
A last possibility is that you're in strict mode. In strict mode, using undeclared variables is forbidden.
Hmm. I made a jsFiddle for you, here: http://jsfiddle.net/5hnPP/1/. Using a "real" button works. You may be running into a DOM issue. Let you know if I find anything more useful.
EDIT: Hmm, even adding the button dynamically works for me. Are you naming your element correctly? (Notice the updated jsFiddle link - has updated markup).