onclick event handler not work - javascript

This is a example code in JavaScript: The Definitive Guide,6th Edition.
<button id="my button">click me</button>
<script>
var b = document.getElementById("my button");
b.onclick = fuction(){alert("Thanks for clicking me!");}; /*work well if I delete this parse*/
b.addEventListener ("click", function(){ alert("Thanks again!");}, false);
</script>
When I click the button, nothing happen.

are you sure you write well?
1 - Remove space on id value: change id="my button" to id="mybutton".
2 - is not fuction, is function.
<button id="mybutton">click me</button>
<script>
var b = document.getElementById("mybutton");
b.onclick = function(){alert("Thanks for clicking me!");}; /*work well if I delete this parse*/
b.addEventListener ("click", function(){ alert("Thanks again!");}, false);
</script>

Your button id can't have a space between the words. Use an underscore instead like <button id="my_button">click me</button>
Also, in your function call for your onclick you spelled function wrong.
See JSFiddle for working example:
https://jsfiddle.net/us2dq8sz/

Wrong spelling in this line
b.onclick = fuction(){alert("Thanks for clicking me!");}; /*work well if I delete this parse*/
fuction instead of function
Working version : https://jsfiddle.net/x46ugomj/

Related

What are some problem solving tips when trying to attach an onclick() function to a button?

I want my button to trigger a download of a PDF file when clicked. However, I am having trouble getting the button to fire the function when clicked. For now, I am just wanting the button to console.log "it works"
I have selected the correct element, and defined the type as "button", and am able to console.log the button. But when attaching the button.onclick()= function{ console.log("it works");}; it does not trigger the console.log in the console. I have also put the onclick function into a window.onload function.
<div id="resume" class="resume">
<button type="button" id="resume-button" class="resume-button">RESUME</button>
</div>
--JavaScript--
var button = document.querySelectorAll('.resume-button');
window.onload = function(){
button.onclick = function(){
console.log("yay its working");
}; }
I am expecting the console to output "it works" when the button is clicked, but nothing happens when clicked.
document.querySelectorAll returns an NodeList so that you need to access the button as the first element of this NodeList (document.querySelectorAll('.resume-button')[0])
var button = document.querySelectorAll('.resume-button')[0];
button.onclick = function(){
console.log("yay its working");
};
<div id="resume" class="resume">
<button type="button" id="resume-button" class="resume-button">RESUME</button>
</div>
Also note there is no need to wrap the onclick function assignment into window.onload

Disable load function untill button is selected in javascript?

Hi this is an odd question and i will try to ask it correctly. I have a function using javascript called load canvas.
function loadCanvas(canvas) {
relevant code here...
}
I also have a normal button called btn.
<button class="btn" type="button">Play!</button>
I am wondering can i disable the function until the play button is selected? The function is for a game using javascript. So on load there isnt anything there until i press play then it appears!
any ideas/help please?
$(document).ready(function(){
var loadCanvas= function (canvas) {
relevant code here...
}
$("#test").on('click',loadCanvas()); // using jquery
document.getElementById("test").addEventListener("click",loadCanvas()); // using javascript
<button class="btn" id="test" type="button">Play!</button>
})
If you are having issue because other method is triggering the function you can add a flag with a boolean and turn it on when you click..
Something like that:
The button don't change at all
<button class="btn" type="button">Play!</button>
The js code with this change:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
And in the on click function add this before call the function:
buttonClicked = true;
At the end your js should look like this:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
$(".btn").click(function(){
buttonClicked = true;
var canvas = ...;
loadCanvas(canvas );
});
EDIT
If you have more buttons with the class .btn you should use an id and change the selector of the .click() with the selector of the id instead of the class selector
As you mentioned in the comments <script type="text/javascript"> loadCanvas("game"); </script> You are calling the function as soon as the page loads. So you will have to change it to:
<button class="btn play-button" type="button">Play!</button>
<script type="text/javascript">
$('.play-button').click(function(e){
loadCanvas("game");}
);
</script>
If you are not using jquery you will have to handle the click event by javascript.
You got to do following:
function loadCanvas(game) {
alert('loading canvas');
}
<button class="btn" type="button" onclick="loadCanvas('game')">Play!</button>

Why is the button disapearing?

The text "Now I'm here..." is supposed to disappear when the button is clicked, not the button itself.
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="remove()">Remove</button>
<script>
function remove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
/*function add()
{
var ele = document.createElement("p");
var text = document.createTextNode("This is new text");
ele.appendChild(text);
var location = document.getElementById("alpha");
location.appendChild(ele);
}*/
</script>
There is another function called remove that is interfering with your function.
Rename your function and it works fine:
http://jsfiddle.net/fL3gZ/
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="Myremove()">Remove</button>
<script>
function Myremove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
</script>
What's happening is remove() is being called on the button itself! HTMLElement.prototype.remove is an existing function (in some browsers)! Oh god!
var button = document.getElementsByTagName("button")[0];
// surprise! this is what's actually happening
button.remove();
Check out this alternative approach. See: fiddle
Change HTML to
<div id="alpha">Now I'm here...</div>
<button type="button">Remove</button>
Then use this JavaScript
function remove(id) {
var elem = document.getElementById(id);
if (elem) elem.parentNode.removeChild(elem);
}
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function(event) {
remove("alpha");
event.preventDefault();
});
A couple things about this:
I'm favoring a more unobtrusive approach
The remove function is single purpose, and reusable
It will work in more browsers
You won't run into WTFs like you just experienced
remove() is already an excisting javascript method, so you are actually calling that method on your button instead of calling the function.
Just rename the function and it will be fine.
Fiddle: http://jsfiddle.net/WkUqT/7/
function removeText()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
You are probably using chrome as your browser to test that code. Elements in chrome have a self-removal, .remove() method which removes the element itself from its container.
This is the main reason why the code above removes the button, because of this the appended event in your onclick() declaration was not invoked because the element invoking the event does not exist anymore. Try changing the name of your function to removeElement().

Bind button to a Javascript case/action

I am new to Javascript, and i run into some big problems. I got some functions, which I can type into a text field and press enter, and the functions works. But i have created 4 buttons, which i want to connect to the actions.. i got 4 actions: "UP","DOWN","LEFT" and "RIGHT".
This is the js fiddle over my code: http://jsfiddle.net/n24gQ/
I have made the buttons like this but I dont know what to write inside the OnClick tag?
<div id="gamebuttons">
<button id="up" button onClick="">UP</button>
<button id="down" button onClick="">DOWN</button>
<button id="left" button onClick="">LEFT</button>
<button id="right" button onClick="">RIGHT</button>
</div>
I hope you can understand what my problem is. I made 4 javascript cases which I want to bind to 4 html buttons if possible.. :) It is the cases: "frem" "tilbage" "hoejre" and "venstre" i need to bind.. Sorry not everything in the code is english, but it should be understandable..
Fiddle
You can simply write the function name you've defined for the buttons into the onclick attribute, e.g. like this:
<button id="up" type="button" onclick="alert('UP'); return false;">UP</button>
However, as your buttons already have id's you can also check if one of those id's got clicked without the need of onclick in your markup:
JavaScript:
var buttonUp = document.getElementById('up');
buttonUp.onclick = function() { myFunction(); return false; }
jQuery:
$('#up').on('click', myFunction());
Instead of using inline handlers (bad practice) or multiple handlers for each button, I would use event delegation on your button wrapper, like so
$('#gamebuttons').on('click', 'button', function() {
/* get the id attribute of the clicked button */
var button_id = this.id;
case (button_id) {
"UP" : /* code for up button */ break;
"DOWN" : /* code for down button */ break;
"LEFT" : /* code for left button */ break;
"RIGHT" : /* code for right button */ break;
}
});
Please pass the function name inside the OnClick tag
for example if you want to associate playGame function to DOWN button
write
<button id="down" onclick="playGame();">DOWN</button>
I think these below changes will give you solution.
Instead of the first button, you need to bind events to all of the buttons which you required. Currently, querySelector() getting only first button to bind events. So, use querySelectorAll()
Replace this code
var button = document.querySelector("button");
button.style.cursor = "pointer";
button.addEventListener("click", clickHandler, false);
button.addEventListener("mousedown", mousedownHandler, false);
button.addEventListener("mouseout", mouseoutHandler, false);
With below code
var gamebuttonslist=document.querySelectorAll("#gamebuttons button");
for (var vitem=0;vitem<gamebuttonslist.length;vitem++) {
if (typeof gamebuttonslist[vitem] != "undefined" && gamebuttonslist[vitem] != null) {
gamebuttonslist[vitem].style.cursor = "pointer";
gamebuttonslist[vitem].addEventListener("click", clickHandler, false);
gamebuttonslist[vitem].addEventListener("mousedown", mousedownHandler, false);
gamebuttonslist[vitem].addEventListener("mouseout", mouseoutHandler, false);
}
}

Javascript click function not working

I'm trying to write a simple javascript function that will clone some html input fields when the user clicks a button, but for some reason the button's click function isn't being called when I click it. Any ideas why?
Here's the javascript:
<SCRIPT LANGUAGE="JavaScript">
$(document).ready(
function(){
$("#default-label").hide();
$("#default-element").hide();
var counter = parseInt($("#counter").val());
$("#addProduct").click(
function(){
var product = $('#fieldset-default');
var newProduct = product.clone(true);
newProduct.insertAfter(product);
document.getElementById("addProduct").innerHTML = 'Add More';
$("#counter").val(++counter);
}
);
}
);
</script>
My HTML for the button:
<button id="addProduct" type="button" name="add">Add Product</button>
i think you missed jquery plugin,included latest version of jquery library, if not there.

Categories

Resources