Javascript "onclick" attribute on button automatically running [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm using a for loop to dynamically name and fill buttons (with text and with code). One thing I had a problem with was dynamically allocating onclick functionality to the buttons, but I seemed to have fixed it with:
document.getElementById(ID_HERE).onclick = FUNCTION();
The problem is when I add this code, the buttons trigger themselves on the load of the webpage instead of the click.
I put the full code below for both the HTML and the Javascript.
JavaScript:
var routes = "";
var elem = "";
var locationid = "50017"
var currentRoute = "the Londinium Way"
function possibleRoutes(){
document.write("<div id='container'>");
document.write("<center><b> Welcome to ");
document.write(currentRoute);
document.write("!<br>")
document.write("Your options are:");
for (i = 0; i<routes.length;i++){
var options = routes[i];
var temp = "button" + i
document.write("<button id='button'></button>");
document.getElementById('button').id = temp;
document.getElementById(temp).innerHTML=routes[i][0];
document.getElementById(temp).onclick = getRoutes(routes[i][1]);
console.log(routes[i]);
console.log(routes[i][1]);
}
document.write("<br><img src='http://192.168.1.151:8000/map.jpg'>");
document.write("</b></center></div>");
}
function getRoutes(locationid) {
var routesURL = 'http://cors.io/?u=http://orbis.stanford.edu/api/sites/' + locationid;
$.ajax({
type: 'GET',
url: routesURL
}).done(function(data) {
console.dir(data);
dataParsed = JSON.parse(data);
currentRoute = dataParsed.prefname;
routes = dataParsed.routes;
console.log(routes);
clearScreen();
});
}
function clearScreen(){
if (document.contains(document.getElementById("container"))){
elem = document.getElementById("container");
elem.remove();
}
possibleRoutes();
}
HTML:
<html>
<head>
<title> Londinium Trail </title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://192.168.1.151:8000/scripts/game.js"> </script>
</head>
<body>
<script>
getRoutes(50017);
</script>
</body>
</html>

JAVASCRIPT
Try to use addEventListener instead :
document.getElementById(ID_HERE).addEventListener("click", myFunction);
JQUERY
If you're using jquery :
$('body').on('click', '#ID_HERE', myFunction);
Take a look at addEventListener vs onclick.
Hope this helps.

The issue is that you are calling the function by using FUNCTION();
Since your code appears to be using JQuery, consider using the .on method to attach a click listening:
$(document).on('click', '#ID_HERE', function(){
function_to_run();
});

Related

Can a javascript file call a function defined in the main html file? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I can't seem to get this to work. I am including a javascript file with functions in it, but one of the functions in the file I want to be defined inside the main HTML file, not the javascript file. This isn't working however.
Here's what I want:
//testFile.js
$(function() {
$(window).scroll(function() {
var Scroll = $(window).scrollTop();
var Width = $(window).width();
var Height = $(window).height();
var Offset;
doParallax();
});
function Parallax(Obj, /*OffX, OffY,*/ ModifierX, ModifierY, Wait) {
var ScrollT = $(window).scrollTop();
var ScrollL = $(window).scrollLeft();
var OffsetY = ScrollT - $(Obj).data("InitialTopOffset");
var OffsetX = ScrollL - $(Obj).data("InitialLeftOffset");
var SpeedX = OffsetX*ModifierX + XOff;
var SpeedY = OffsetY*ModifierY + YOff;
if (Wait) {
if (ScrollT >= $(Obj).data("InitialTopOffset")) {
$(Obj).stop(true, false).css( "background-position", (ScrollL+SpeedX) + "px " + (-OffsetY-SpeedY) + "px", 50, "linear");
}
}
else {
$(Obj).stop(true, false).css( "background-position", (ScrollL+SpeedX) + "px " + (-OffsetY-SpeedY) + "px", 50, "linear");
}
}
});
//
//main HTML file
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function doParallax() {
XOff = ( $(window).width() - ( $(window).width()*0.9 ) ) / 2;
Parallax(".parallax3", 0, -0.55, true);
}
</script>
<script src="testFile.js"></script>
</head>
<body>
...
</body>
</html>
I haven't been able to find anything from doing google searches or from searching on Stack Exchange. But assuming that it isn't working means that I can't do this, but is there a way to achieve the desired result?
EDIT: Actual code examples
This is invalid:
<script src="testFile.js">
function somethingElse() {
alert("Called");
}
</script>
A script tag either references a script or contains a script. Not both. Separate them into their own tags:
<script src="testFile.js"></script>
<script>
function somethingElse() {
alert("Called");
}
</script>
(Of course, this is ignoring the fact that the contrived example never calls doSomething(), but I assume that's just an oversight in the example.)
Note also that there may be a scope issue depending on when you call this function. If doSomething() is invoked before somethingElse() is in scope, that could be a problem. You may be able to hoist it to the top of the current scope by defining it like this though:
var somethingElse = function() {
alert("Called");
}
Not sure if that's even an issue here though, since the code in the question doesn't actually invoke any functions.
Edit: Since the question has drastically changed...
In a comment above you mention the problem:
The console is actually now saying that Parallax() is not defined.
This is because that function exists only within the scope of the function you're using in the document.ready handler. To simplify:
$(function () {
// anything created here only exists here
});
// so you can't call it here
If you have functions which need to be invoked outside that scope, define them outside of that scope:
$(function () {
// perform document ready handler actions here
});
var Parallax = function() {
//...
}
var doParallax = function() {
//...
}

How to use event listener in JS

Im trying to use the same buttons for different function in the program. So I tried using event listeners but for some reason its not working. Could look at the code and tell me what I have done wrong? Thanks. (I omited the HTML tags and so for shortening the posted code)
<script type="text/javascript">
var photo = "photo";
var edgar = "edgar"
var x = document.getElementById("yes");
x.addEventListener("click", choiceyesstory);
x.addEventListener("click", choiceyesfriendly);
var y = document.getElementByID("no");
y.addEventListener("Click", choicenostory);
y.addEventListener("click", choicenofriendly);
function choiceyesstory(x) {
document.getElementById("photo").src = "images/dragon1.jpg";
document.getElementById("stage1").innerHTML = "Once upon a time";
setTimeout("choice2()",5*1000);
}
function choicenostory(y) {
document.getElementById("photo").src = "images/sea.jpg";
document.getElementById("stage1").innerHTML = "Would you like to
listen to some music?";
document.getElementById("edgar").play();
}
function choice2(x){
document.getElementById("photo").src = "images/dragon9.jpg";
document.getElementById("stage1").innerHTML = "Was he a friendly
dragon?";
}
function choiceyesfriendly(x) {
{document.getElementById("photo").src = "images/dragon2.jpg";
document.getElementById("stage1").innerHTML = "He had many friends";
}
function choicenofriendly(y)
{ document.getElementByID ("photo").src = "images/dragon3.jpg";
document.getElementById("stage1").innerHTML = "He did so and so";
}
</script>
<body>
<button id="yes">Yes</button>
<button id="no">No</button>
</body>
Edit / Delete Edit Post Quick reply to this message Reply Reply With Quote Reply With Quote Multi-Quote This Message
Reply to Thread
Quick Navigation DOM and JSON scripting Top
Quick Reply Quick Reply
I took yours js and simplified it. The event listener by itself is working ok. Maybe you have issue somewhere else.
http://jsfiddle.net/jnmav1wk/
var x = document.getElementById("yes");
console.log(x);
x.addEventListener("click", choiceyesstory);
function choiceyesstory(x) {
alert('Clicked');
}
Try to simplify your problem, get rid of the NO and all corresponding code, keep removing code till it's working. Then add feature by feature till it will stop working and you know where it's broken.
I use console.log(); and alert(); to make it more verbose to me.
Sometimes the code needs to be inside this:
$( document ).ready(function() {
yourCode();
});
This needs jQuery, if you want avoid it, here are some alternatives:
$(document).ready equivalent without jQuery
Because if the functions are executed against HTML code which is in middle of loading (and maybe the YES button is not there yet while you try to attach the event listener to it, etc...)

why is this if statement not doing anything? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Believe me the HTML won't be necessary on this one since the if statement only deals with the cBox variable. What this does is, create or close a div upon clicking a button, i've tested the functions and they work, what's not working however is the way these functions are called, I've logged the outputs but i get neither of them displayed in the console, this means the code is not running through the if statement for some reason.
Also tried with if (cBox == null) and it doesn't work ...
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('cBox');
console.log(" but cbox is "+cBox);
if(cBox) {
closecBox();
console.log("cbox exists, closing ...");
} else {
opencBox();
console.log("cbox does not exist, creating...");
}
};
I am not sure i understand your question but if your code is like this seems to work fiddle
function closeBox(elem){
elem.parentNode.removeChild(elem);
}
function openBox(el){
var el = document.createElement('div');
el.setAttribute("id", "cBox");
document.body.appendChild(el);
}
var btnPress = document.getElementById('button');
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('cBox');
if(cBox) {
closeBox(cBox)
console.log("cbox exists, closing ...");
} else {
openBox(cBox);
console.log("cbox does not exist, creating...");
}
};
If i did not understand your question sorry for having done wasting time.
Guys thank you for all the replies, your hints were definitely helpful for solving this problem, i made so many changes that i lost track but this is the working code
var btnPress = document.getElementById('theBtn');
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('confirmBox');
console.log("cbox is "+cBox);
if(cBox) {
console.log("cbox exists, closing ...");
closecBox();
} else {
opencBox();
console.log("cbox does not exist, creating...");
}
};
function opencBox() {
var cBox = document.createElement('div');
cBox.id = "confirmBox";
document.body.appendChild(cBox);
cBox.style.display="inline";
};
function closecBox() {
var cBox = document.getElementById('confirmBox');
cBox.style.display="none";
document.body.removeChild(cBox);
};
I also used display style to test some other stuff with animations :) once again, thank you so much for all the comments! They really helped me out figuring the solution!

How can I dynamically add a class to 'body' using JavaScript only for the home page?

I added this to the head, but it's not working:
<script>
var xpathname = (window.location.pathname);
if (xpathname ==('/')) {
$('body').addClass('home');
}
</script>
The site is here: http://xotdr.unxpr.servertrust.com/
Volusion doesn't allow developers to code freely so there are a lot of workarounds that I need to implement, unfortunately.
Edit: I want the class to show only on the home page body.
Since you added this to the head you need to execute this snippet when body tag is available:
$(function() {
var xpathname = window.location.pathname;
if (xpathname == '/') {
$('body').addClass('home');
}
});
<script>
var bodyclass=document.createAttribute("class");
bodyclass.value="home";
document.getElementsByTagName("body")[0].setAttributeNode(bodyclass);
</script>
Give this a try
var b = document.getElementsByTagName('body')[0];
b.className += 'home';
I know it's a old post, but the question will remain useful.
var xpathname = (window.location.pathname);
var ndeBody = document.getElementsByTagName("body")[0];
if (xpathname ==('/')) {
ndeBody.classList.toggle("home");
}
else{
ndeBody.classList.toggle("home");
}
When I go to that URL you have syntax error:
Uncaught ReferenceError: x$ is not defined
e.g. you want to delete the x in x$('body').addClass('home');

Do I need to load JQuery to make this work?

I have two drop down boxes that represent year intervals. The user will select a year from the first one (say 2002), and the next drop down box will automatically be filled with years that equal or are greater than the first (2002 and above). I believe I have the correct javascript code (year.js).
Here it is:
$("#first").change(function(){
var val = $("#first option:selected").html();
$("#second").html("");
var d = new Date();
var n = d.getFullYear();
for (i=val; i<=n;i++){
$("#second").append("<option>" + i + "</option>");
}
});
Here is part of my html form code:
<body>
<script src="year.js"></script>
<select id= "first">
// Here, I gather my years from my database
</select>
<select id= "second">
</select>
When I run this, Nothing happens with my second drop down menu. Do I need to load something else into my code like JQuery? If so, how do I do that? Sorry, I am not very familiar with JQuery. Any help would be greatly appreciated.
Yeah you need to load jQuery library to use jQuery function.
you must load the jQuery library before using it's function.
example
<script src="jquery.js"></script> //a local version
or
<script src="http://code.jquery.com/jquery-latest.min.js.js"></script>
<script src="year.js"></script>
Download jQuery library from http://jquery.com/download/
Updated after OP's comment about http://jsfiddle.net/YNuna/1/
you have laoded jQuery library in fiddle.I have marked it with red color in the image below.
also wrap you code in $(document).ready(function ()
$(document).ready(function () {
$("#first").change(function () {
var val = $("#first option:selected").html();
$("#second").html("");
var d = new Date();
var n = d.getFullYear();
for (i = val; i <= n; i++) {
$("#second").append("<option>" + i + "</option>");
}
});
});
If you're copy-pasting javascript code from anywhere and you see a $ sign, a good rule of thumb is that it uses jQuery.
See here for adding it to your page: http://learn.jquery.com/about-jquery/how-jquery-works/

Categories