Multiple onclick events in Javascript/html - javascript

How can I create multiple onclick events for my html buttons? The code I have right now only implements it for one button. How can I get the script to change the image src to different images when the other buttons are clicked. I tried using different functions for each button but that didn't work.
*
<body>
<button class="button" onclick="myFunction()" ><strong>Objectives</strong></button>
<button class="button"><strong>Mission</button></strong>
<button class="button"><strong>Chemistry Vision</strong></button>
<button class="button"><strong>Environment Vision</strong></button></br>
<img id="myImg" src="http://image.png" >
<script>
function myFunction() {
document.getElementById("myImg").src = "http:Objectives.png";
}
</script>
</body>
*

You should pass parameter to the function, something like this:
<body>
<button class="button" onclick="myFunction('Objectives')" ><strong>Objectives</strong></button>
<button class="button" onclick="myFunction('Mission')"><strong>Mission</button></strong>
<button class="button" onclick="myFunction('Chemistry)"><strong>Chemistry Vision</strong></button>
<button class="button" onclick="myFunction('Environment')"><strong>Environment Vision</strong></button></br>
<img id="myImg" src="http://image.png" >
<script>
function myFunction(imgName) {
document.getElementById("myImg").src = "http:" + imgName + ".png";
}
</script>
</body>

Related

Why is my javascript src not loading in HTML?

As of now, I am making a simple no internet dinosaur game that everyone is familiar with using HTML, JS and CSS. I have been working my way through it and I have gotten everything working for the past few hours. All of a sudden, my buttons weren't working giving me the error: Uncaught ReferenceError: start is not defined at HTMLButtonElement.onclick
I tried changing the functions of the buttons and the IDs but none of it worked. My conclusion is that my script.js file isn't loading with the HTML file for whatever reason but the .css file is. The following code is the HTML.
<div id="game">
<div id="character"></div>
<div id="block"></div>
</div>
<div>
<button class="btn btn-secondary" id="button" onclick="start()">Start</button>
<button class="btn btn-secondary" id="button2" onclick="pause()">Pause</button>
</div>
</body>
<p id="paused"></p>
<p id="score"></p>
<script src="script.js"></script>
</html>
The code below is the code for either function.
function start() {
document.getElementById("button").innerHTML = 'Jump'
button.setAttribute( "onclick", "jump()")
block.classList.add("movement")
}
function pause() {
pauseStatus = true
}
I don't know what the problem might be. I haven't made any changes to the file paths or anything and I can't think of how to fix the problem. I've tried putting the src path both in the body and outside of the body in the HTML and it hasn't worked.
You should try moving your script tag inside your body.
<div id="game">
<div id="character"></div>
<div id="block"></div>
</div>
<div>
<button class="btn btn-secondary" id="button" onclick="start()">Start</button>
<button class="btn btn-secondary" id="button2" onclick="pause()">Pause</button>
</div>
<p id="paused"></p>
<p id="score"></p>
<script src="script.js"></script>
</body>
</html>
Javascript
You should also be mindful that lines of Javascript should terminate with a semicolan.
function start() {
document.getElementById("button").innerHTML = 'Jump';
button.setAttribute( "onclick", "jump()");
block.classList.add("movement");
}
function pause() {
pauseStatus = true;
}
It would also be wise to take note of Sebastians suggestion and use addeventlistener for event handling.
button.addEventListener("click", jump);

Count Click Only Once

Here is my code:
<html>
<body>
<script>
var clicks = 0;
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
</script>
<p>Clicks: <a id="clicks">0</a></p>
<button type="button" onClick="clickME()">Click me</button>
<button type="button" onClick="clickME()">Click me</button>
<button type="button" onClick="clickME()">Click me</button>
<button type="button" onClick="clickME()">Click me</button>
</body>
</html>
I'm trying to use this example I found:
<body>
<h1>Single click JS Button</h1>
<button type="submit" onClick="this.disabled = true; return true;">Submit</button>
</body>
I'm confused on how to use the onClick="this.disabled = true; part because for my code I already have the function called when I wrote onClick. I used onClick="clickMe().
Are you allowed to have onClick twice? I want to use the onClick="this.disabled = true; because I don't want to keep increasing the amount of clicks if the user clicks the button again. If they click it once I only want to increment once and then disable the button or just not increase the count after.
Note on possible duplicate
I do not think this is a duplicate of the other question, as that is jQuery click() only once, but I'm using JavaScript. I have not learned jQuery (jQuery click() only once)*
Please take a look here:
var clicks = 0;
function clickME(el) {
el.disabled = true;
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
<p>Clicks: <a id="clicks">0</a></p>
<button type="button" onClick="clickME(this)">Click me</button>
<button type="button" onClick="clickME(this)">Click me</button>
<button type="button" onClick="clickME(this)">Click me</button>
<button type="button" onClick="clickME(this)">Click me</button>
addEventListener option once:true - looks like a perfect option in your case.
More explanations in the code
var clicks = 0
function clickME(event) {
clicks += 1
document.getElementById("clicks").innerText = clicks // innerText is more suitable in this case
if (event.target.className.includes(`auto-disable`)) {
event.target.disabled = true // auto disabling if you need it
}
}
document.querySelectorAll(`button`) // select all buttons
.forEach( // loop through the elements
// addEventListener with options once:true. once option designed exactly for your purposes, to fire event only once
el => el.addEventListener(`click`, clickME, {once: true})
)
<p>Clicks: <a id="clicks">0</a></p>
<button type="button">Click me</button>
<button type="button">Click me</button>
<button type="button" class="auto-disable">Click me</button>
<button type="button" class="auto-disable">Click me</button>

Simple javascript function doesn't work when placed outside of tag [duplicate]

This question already has answers here:
Why does this simple JSFiddle not work? [duplicate]
(8 answers)
Closed 5 years ago.
I have a function that changes a paragraph's content:
function test() {
document.getElementById("demo").innerHTML = "ops2"
}
When used inside a tag it works fine:
<button type="button" onclick='document.getElementById("demo").innerHTML = "ops"'>Change Content</button>
However when placed outside in a function it doesn't work:
<button type="button" onclick=test()>load</button>
Here is a jsfiddle. What am I doing wrong?
Its just matter of sequence of script and html code. When I put test function on top of html code, and then called the function with onclick="test()" it worked well.
So here is what I did: (Notice the Change Content button tag.)
<script>
function test(){
document.getElementById("demo").innerHTML = "ops2"
}
</script>
<h3 id="demo">Hello</h3>
<p>Here is some text</p>
<center>
<img id="lamp" src="https://www.w3schools.com/js/pic_bulboff.gif"/>
<br/><br/><br/>
<button type="button" onClick='test()'>Change Content</button>
<br/><br/><br/>
<button type="button" onClick='document.getElementById("lamp").src = "https://www.w3schools.com/js/pic_bulbon.gif"'>Light</button>
<button type="button" onclick='document.getElementById("lamp").src = "https://www.w3schools.com/js/pic_bulboff.gif"'>Dark</button>
<button type="button" onclick='document.getElementById("lamp").src = ""'>Hide</button>
<button type="button" onclick='document.getElementById("lamp").src = "https://www.w3schools.com/js/pic_bulboff.gif"'>Show</button>
</center>

Trying to make a button in JavaScript but it's not working

I'm new in JavaScript and I took an app here to learn how to use the language.
So, In my index.html I have this code here:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
and this as footer:
`<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>`
What I'm basically trying to do is just reset the score to zero. But It's not working...
I tried to put some alert() inside reset() function but didn't work also.
Does someone has a clue why this is happening?
Thanks for helping!
Use onclick property:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore" onclick="reset()">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
You are declaring the function but not calling it anywhere. So you need to call the function at onclick event of button.
You should add an event listener for the click event.
Because of your comment, you can change the DOM by changing the inner HTML, see below snippet and code:
document.getElementById('resetscore').addEventListener('click',function() {
//localStorage.setItem('total_win', 0);
//localStorage.setItem('total_lose', 0);
document.getElementById('total_win').innerHTML = 0;
document.getElementById('total_lose').innerHTML = 0;
});
document.getElementById('win').addEventListener('click',function(){
var a = parseFloat(document.getElementById('total_win').innerHTML);
document.getElementById('total_win').innerHTML = (a+1).toFixed(0);
});
document.getElementById('loss').addEventListener('click',function(){
var b = parseFloat(document.getElementById('total_lose').innerHTML);
document.getElementById('total_lose').innerHTML = (b+1).toFixed(0);
});
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<button type="button" id="win">+1 Win</button>
<button type="button" id="loss">+1 Loss</button>
</div>
<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>
your script tag can't be inside a div. You need to move all your javascript to the end of your body, right before its closing tag, after all the html
Just add this:
<button type="button" onclick="reset()" id="resetscore">
You need to tell which one of your functions to use, notice the onclick, it does just that, so reset executes on click
Your button needs to call reset
<button type="button" id="resetscore" onclick="reset()">Reset</button>

How to disable HTML button on the click using Javascript?

Once my button gets clicked, it should get disabled and never be clicked again until the page is refreshed. Below is my code:
<html>
<head>
<script type="text/javascript">
function myButtonClicked()
{
alert("Has myButton got disabled? I need solution for this.");
}
</script>
</head>
<body>
<button type="button" id="myButton1" onclick="myButtonClicked()">Click ME</button>
<button type="button" id="myButton2" onclick="myButtonClicked()">Click ME</button>
<button type="button" id="myButton3" onclick="myButtonClicked()">Click ME</button>
</body>
</html>
Before calling myButtonClicked function, it should get disabled. Actually, I want to write a PHP script in this function which will fetch some data from database which will take some time in real environment. That is why I want to disable the button. How do I achieve that?
You can pass this to your function:
<button type="button" id="myButton1" onclick="myButtonClicked(this)">Click ME</button>
<button type="button" id="myButton2" onclick="myButtonClicked(this)">Click ME</button>
<button type="button" id="myButton3" onclick="myButtonClicked(this)">Click ME</button>
then you can use:
function myButtonClicked(el)
{
el.disabled = true;
}
Fiddle Demo
with jQuery you can use .click() along with .prop():
$('button').click(function() {
$(this).prop('disabled',true);
});
Fiddle Demo
function myButtonClicked()
{
$(this).prop('disabled', true);
}
Is it helping?
Add -
function myButtonClicked()
{
alert("Has myButton got disabled? I need solution for this.");
this.disabled = true;
}
Give your element as an argument within calling teh function
<button type="button" id="myButton1" onclick="myButtonClicked(this)">Click ME</button>
<button type="button" id="myButton2" onclick="myButtonClicked(this)">Click ME</button>
<button type="button" id="myButton3" onclick="myButtonClicked(this)">Click ME</button>
And set the element attribute "disabled" to true
function myButtonClicked(obj) {
obj.setAttribute("disabled", true);
}
fiddle: http://jsfiddle.net/quJX8/
JSBIN
$("button").click(function() {
$('#'+this.id).prop('disabled', true);
});
You can disable like this, this is self explainable:
<script>
function myButtonClicked(id)
{
alert("Has myButton got disabled? I need solution for this.");
$("#" + id).attr("disabled", true);
}
</script>
<body>
<button type="button" id="myButton1" onclick="myButtonClicked(this.id)">Click ME</button>
<button type="button" id="myButton2" onclick="myButtonClicked(this.id)">Click ME</button>
<button type="button" id="myButton3" onclick="myButtonClicked(this.id)">Click ME</button>
</body>
There are simpler ways than rewriting your function and passing "this". Just use "this" in your onclick attribute:
<button type="button" id="myButton1" onclick="this.disabled=true;myButtonClicked()">Click ME</button>
That will disable it, but it isn't necessarily that visibly obvious on the form. I like to use:
<button type="button" id="myButton1" onclick="this.style.visibility='hidden';myButtonClicked()">Click ME</button>
Which "disappears" it, but it still holds its place in the form.
If you don't need the placeholder, you can also use:
<button type="button" id="myButton1" onclick="this.hidden=true;myButtonClicked()">Click ME</button>

Categories