Javascript - 2nd button click clears my div - javascript

im fairly new to JS and ive created a formula to do some calculations and put them into a div when its done. My problem is on the first button press it works like a charm. When i press the button a second time it deletes the text in my div and doesnt redo the calculation.
Its probably some silly mistake i cant find but id appreciate any help. The Code looks like this:
function formChanged() {
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
}
document.getElementById('button').click = function calc() {
var x = parseFloat(document.getElementById("x").value);
var y = parseFloat(document.getElementById("y").value);
document.getElementById("test").innerHTML = "pre-text";
while (y < x) {
document.getElementById("test").innerHTML += "text" + x + "more text";;
y++;
}
document.getElementById("test").innerHTML = "post-text";
}
<form>
<input value="20" id="x" type="text" onkeyup="formChanged()" onchange="formChanged()">
<input value="1" id="y" type="text" onkeyup="formChanged()" onchange="formChanged()">
<button type="button" id="button">Calc</button>
</form>
<div id="test" style="height:400px; width:500px; overflow-y: scroll;"></div>
I tried to slim it down a bit since its a bigger loop with calculation etc. The function itself works fine though.

document.getElementById("test").innerHTML = "post-text";
this part removes your div content, just change it with :
document.getElementById("test").innerHTML += "post-text";
Calc
Full working code:
<div id="test" style="height:400px; width:500px; overflow-y: scroll;"></div>
<script>
function calc() {
var x = parseFloat(document.getElementById("x").value);
var y = parseFloat(document.getElementById("y").value);
document.getElementById("test").innerHTML = "pre-text";
while (y < x) {
document.getElementById("test").innerHTML += "text" + x + "more text";;
y++;
}
document.getElementById("test").innerHTML += "post-text";
}
</script>
And ofcourse you can use element.addEventListener("click", calc)like SimpleJ mentioned.
document.getElementById('button').addEventListener("click", calc);

I copied your code into a file and tried it. Your button doesn't do anything.
Edit: As #SimpleJ stated, calling globally is a bad practice. I updated the answer.
function calc(){
// function body
}
document.getElementById('button').addEventListener("click", calc);
This way the calc() function is actually called when you click the button. It's called adding an EventListener if you need some term to Google for further reference.
I hope this is what you need.

Related

Script not working on first click only on second

I'm new to js and I have this problem
I want on click to change a height of one element to width of another element
and this code works properly by for some reason I have to click twice, any suggestions how to make it to work on first click?
<script>
var l = document.getElementById("tablinks");
l.onclick = function(){
var w = document.getElementById("img1").offsetWidth;
document.getElementById("beforeafter1").style.height = w + "px";
};
</script>
Try below script.
<script>
//var l = document.getElementById("tablinks");
function doMyTrick(){
var w = document.getElementById("img1").offsetWidth;
document.getElementById("beforeafter1").style.height = w + "px";
};
</script>
<input type="button" onclick="javascript:doMyTrick()" value="Submit"/>
The link/button code is missing, but I guess you didn't put return false; to your javascript code:
<a href='#' id="tablinks" onclick='someFunc(3.1415926); return false;'>Click here !</a>

How to Change a Value of a Variable and Print It

Sorry, I'm totally new to javascript and need help with something you think is probably really stupid.
I'm trying to make it so that when you start the program, it prints 0, then when you press a button, it changes 0 to 1. This is what I have so far -
<!DOCTYPE html>
<html>
<p id="print"></p>
<script>
var x = 0
document.getElementById('button').onclick = function() {
x++;
};
document.getElementById("print").innerHTML = x;
</script>
<button id = "button">Change Variable x</button>
</body>
</html>
Although, it doesn't print anything when I run the code. Please Help! (By the way, you are probably thinking that this is a stupid question.)
Thanks!
I hope this will work:
var x = 0
document.getElementById('button').onclick = function() {
x++;
document.getElementById("print").innerHTML = x;
};
Not sure if this is what you are looking for, but all I did was make a function name and then whenever you click the button it adds 1 to the
<p id="print">hello</p>
<button id = "button" onclick="myFunction()">Change Variable x</button>
<script>
var x = 0
function myFunction(){
document.getElementById('print').innerHTML = x+=1;
}
</script>
Here is a working snippet of what you are looking for, using javascript. When the user clicks the button, it changes the value to 1, and then when you click the alert button it alerts 1 instead of 0.
var changeMe = 0;
function changeVar() {
changeMe = 1;
}
function alertVar() {
alert(changeMe);
}
<button onclick="changeVar();">Change</button>
<button onclick="alertVar();">Alert</button>

How can I make something move in javascript?

I made a div and a button. Made a function on button's click that set div's margin (i.e move it). But how can I make it move on every click. Whenever I hit the button it do moves, (without refreshing the page) when I press that button again it don't work? How to make it move on every click of button! Here's my code:-
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
<style>
body
{
font-family:ebrima;
}
</style>
</head>
<body onload="" id="demo">
<div name="player" style="float:right; height:32px; width:32px; background:green;" id="myDiv"></div>
<form name="myForm" method="post">
<button value="MOVE" type="button" name="moveButton" onClick="move()">MOVE</button>
</form>
<script>
function move()
{
document.getElementById("myDiv").style.margin="0px 10px 0px 0px";
}
</script>
</body>
</html>
Use a variable to set the new margin each time. After using it, change the variable's value so that next time, it will move somewhere else.
var x = 10;
function move() {
document.getElementById("myDiv").style.margin="0px "+x+"px 0px 0px";
x = x+10;
}
First, don't use inline js (like onclick). Read some of these results: *Why is inline js bad?*
Instead, attach your event listener with javascript:
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
Your code would be more readable/efficient and easier to debug like this:
//cache element reference in advance
var document.getElementById("myDiv")
function move() {
//just target the property you want to change.
myDiv.style.marginLeft = x+'px';
x = x+10;
}
Here's a little demo (click) I put together you may enjoy.
var myDiv = document.getElementById('my-div');
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
function move(e) {
var v = r()+'px '+r()+'px '+r()+'px '+r()+'px';
myDiv.style.margin = v;
}
function r() {
return getRandomInt(0, 20);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
And here's a more fun one using mousemove rather than click. Demo here.
I would advise using jQuery, which makes a lot of javascript quite simple.
Here's a sample jQuery animation for you:
<script>
function move() {
$("#myDiv").animate({left:'+=250px'});
}
</script>
This will shift the button over by 250px every time you trigger the function.
Note that you'll need to add jQuery to your project (which is trivial). The jQuery website has some well organized tutorials that should help you find your way around JavaScript and jQuery - happy coding!
Like this:
function move() {
var elt = document.getElementById("myDiv"),
currentMargin = parseInt(elt.style.marginRight, 10);
elt.style.marginRight = currentMargin + 10 + 'px';
}

How can I change a modal popup every 30 seconds?

I have a div id called modalpage
and have css. I need a javascript function which can dynamically shows popup for 20 mins and change in every 30 secs right now i have the following javascript function. Can anybody help me please
<script language="javascript" type="text/javascript">
function revealModal(divID)
{
window.onscroll = function () {
document.getElementById(divID).style.top = document.body.scrollTop;
};
document.getElementById(divID).style.display = "block";
document.getElementById(divID).style.top = document.body.scrollTop;
}
which is called by a input id button.
<input id="Button1" type="button" value="Click here" onclick="revealModal('modalPage')" />
Thanks
This is what i came up with
function revealModal(divID)
{
var i = 1;
divID.replace('*', i);
setInterval(function(){revealModal(divID)},1000);
i = i + 1;
if (i == 3) i = 1;
var div = getElementById(divID)
window.onscroll = function () { document.getElementById(divID).style.top = document.body.scrollTop; };
document.getElementById(divID).style.display = "block";
document.getElementById(divID).style.top = document.body.scrollTop;
}
but this is not working its showing the modular_3 every time. is it because of all three divs are in the same file ??
<input id="Button1" type="button" value="Click heres" onclick="revealModal('modalPage_*')" />
Well, for one thing don't put that set interval inside the function. That would start a never ending cycle on the first click that would keep triggering the div id it was passed.
What you should probably do is keep an array of id's that should be updated and loop through that in the function...
var divs = [];
function addID(id)
{
divs.push(id);
}
function revealModal()
{
for(var i = 0; i < divs.length; i ++)
{
var div = getElementById('modalPage_' + divs[i]);
window.onscroll = function () {
div.style.top = document.body.scrollTop;
}
div.style.display = "block";
div.style.top = document.body.scrollTop;
}
}
setInterval(function(){revealModal()},1000);
And your html buttons:
<input id="Button1" type="button" value="Click heres" onclick="addID('1')" />
<input id="Button2" type="button" value="Click heres" onclick="addID('2')" />
<input id="Button3" type="button" value="Click heres" onclick="addID('3')" />
Now consider this - I don't really understand your request. It looks like a bunch of others don't understand either. The way I saw it was you want to reveal a div on click and make sure it updates every nth seconds. In this case, it looks like you chose 1000 ms, or every 1 second even though you said you wanted every 30 seconds. Fair enough, change that 1000 to 30000.
It looks like the ONLY update you do is make sure it sticks to a certain position on the screen and NOT updates the content.
So what I've done is make the interval outside the function so it is always going. Then on click you push the id into the divs array where the interval will update only what is inside the loop. While conceptually this will work, it seems like a bad way to do it.
You should just use an easy library like jquery and place a scroll listener that updates the position whether or not they're revealed. Seeing as you specified jquery in your tags but don't use a lick of it in your example, I assume that means you're not entirely familiar with the library.
This could be done by simply adding a class of "modal" to every modal div and using this:
$(document).ready(function(){
$(window).scroll(function(){
$('.modal').css('top', $(window).scrollTop() + 'px');
});
$('.modal').on('click', function(){
$(this).css('display', 'block');
});
});
Of course you would need to call the jquery library before this call for this to work.

How to change the function called by a dynamically created button?

I was making a little game in JavaScript when I ran into a problem. In this game I create a hundred buttons using a for() loop. Eventually I want every button to call a function called 'click' and send it an int so it knows what button is pressed. So for instance when button four is pressed click(4) is called. First I tried this:
object.onclick = "click(4)";
That obviously didn't work so i searched the interwebs and fount an answer to this question on your site.
object.onclick = function() {click("4");}
I tried that (with and without the ';' at the end) but it doesn't seem work.
A more complete overview of the dummy code:
<script type="text/javascript">
document.getElementById('myContainer').innerHTML += '<input id="tmp" type="button" value="button">';
documengetElementById('tmp').onclick = function() {tmpFunc("bla");}
function tmpFunc(vari){
alert(vari);
}
</script>
The element myContainer is 100% empty!
Remember, this is just dummy code to try it out. I could do this waaaaay easier but I tried to simplify it first so you don't have to look at my messy code.
So what is the best way to call a function from a button you have created in a for loop? If you know a way to do it totally different from the one I use just post it, I don't care how it gets solved! Although I'd also like somebody to explain why this isn't working.
Hope I didn't ask a question already answered, as far as I know I'm using the solution given for this problem in another post.
------------UPDATE-------------
Changed it a bit after getting an answer from somebody. This is the current code, select() isn't executed when a button is pressed. Here's the complete JavaScript code so you can copy-paste it if you want to play around with it.
<script type="text/javascript">
function addButtons(){
var disabled = false;
for(var i = 1; i <= 100; i++){
currentButton = '<input id="tmp" type="button" onclick="select(\''+i+'\')">'
document.getElementById('myContainer').innerHTML += currentButton;
document.getElementById('tmp').id = 'btn'+i;
gb(i).disabled = disabled;
gb(i).style.width = "60px";
gb(i).style.height = "60px";
gb(i).style.fontSize = "25pt";
function alerts(nr){
alert("test");
}
if(i%10 == 0){
document.getElementById('myContainer').innerHTML = document.getElementById('myContainer').innerHTML + '<br />';
}else{
if(disabled){
disabled = false;
}else{
disabled = true;
}
}
if(i == 60){
gb(i).value = 'O';
gb(i).style.color = "blue";
}
if(((i-1)%10 == 0) && !(gb(i).disabled)){
gb(i).value = 'X';
gb(i).style.color = "red";
}
}
}
function select(nr){
alert("Bla!"+nr);
gb(nr).style.height = "100px";
}
function gb(ButtonNrVanHetButton){
return document.getElementById('btn'+ButtonNrVanHetButton);
}
addButtons();
</script>
Most parts aren't very interesting for solving the problem (style etc) It's supposed to look like a checkerboard.
------------UPDATE-------------
Solved! Don't use functions the javascript library already uses for other stuff like: 'select()'. Thx to everybody who tried to help!
If you are looping to create the buttons, why don't you add an onclick to the button?
for instance
<script>
// your function
function tmpFunc(vari)
{
alert(vari);
}
// end your function
// define xBUTTONS
xBUTTONS = '';
for (i=0; i<100; i++)
{
// loop buttons
xBUTTONS += '<input id="tmp" type="button" value="button" onclick="tmpFunc(\''+i+'\')">';
}
// insert buttons into myContainer
document.getElementById('myContainer').innerHTML = xBUTTONS;
</script>
first off, always attach events by using addEventListener. second, if you add an id to the button you dynamicly generate you can do something like this;
function click(){
alert(this.id+" clicked");
}
var but;
for (var i=0,e=100,i<e;++i){
but=document.createElement("input");
but.id=i;
...//make it into your button
but.addEventListener("click", click, false);
document.body.appendChild(but);
}

Categories