Bind button to a Javascript case/action - javascript

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);
}
}

Related

How do I remove an eventListener after a button-click?

I've got a content editable div like this:
<div id="editor" contenteditable="true">
And I've got two buttons:
<div id="button1" onclick="javascript()">
<div id="button2" onclick="javascript()">
Both buttons call the same javascript-function, so this function will be repeated every time you click on one of the buttons. For example:
When I click on button1, the script adds an Eventlistener to the editor. I use this to save the content of the editor on certain keystrokes.
When I click on button2, the eventlistener needs to be removed and a new one needs to be added. How can I do that?
I already tried this:
function javascript() {
// remove the eventlistener
editable.removeEventListener('keydown', keydownsave, true);
var editable = document.getElementById('editor');
editable.addEventListener('keydown', keydownsave, true);
keydownsave = function(e) {
// execute only if certain keys are pressed.
var toets = e.keyCode;
var ctrls = e.ctrlKey;
if (toets == 32 || toets == 13 || ctrls == true && toets == 83)
But this didn't work.
You can use unbind to do this. unbind
$('#t').click(function() {
alert('clicked')
})
$('#t').on('mouseover',function() {
$(this).html('mouse over')
})
$('#t').on('mouseout',function() {
$(this).html('button with event listeners')
})
function removeEventListeners() {
$('#t').unbind()
$('span').html('this button has no events')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id=t>button with event listeners</button>
<span>this button has click, mouse over and mouse out event</span>
<br>
<button onclick="removeEventListeners()">remove event listeners</button>
I actually create a bunch of these div-buttons on the fly:
<div id="subchaptertitle" data-chapid="1" data-subid="1" onclick="javascript:open_editor()">bos in brand</div>
Each button has different data and with onclick they start the function open_editor.
In this way, a new instance of the function is called every time you click on one of the buttons. But these functions never close, which means they keep running in the background, breaking the way I save stuff.
What I actually need is to end the previous function with it's eventListener, before the same function is called again. Is this possible in JavaScript?

Prevent onclick from firing

I was working around with form submissions in html. Please take a look at below code
<form id="form1">
<button id="btn1" onclick="clicked();">Submit</button>
</form>
<script>
$("#btn1").click(function (event) {
alert("event triggered");
if(some_condition == true){
// stop firing onclick method but it always submits the form
event.stopImmediatePropogation(); // not working
event.preventDefault(); // not working
event.stopPropogation(); // not working it's for bubbled events
}
});
function clicked(){ alert("clicked me"); }
</script>
I want to stop clicked() function from firing which is attached to inline onclick attribute. I would like to run my jquery click function and if something goes wrong, I dont want to trigger onclick but it always runs clicked() function. Could any one help me. Any help is greatly appreciated.
The order in which an onxyz handler is called relative to dynamically-attached handlers varies from browser to browser, so your handler may well not run before the original does.
To deal with that, you save and remove the onclick handler:
var btn = $("#btn1");
var clickHandler = btn[0].onclick;
btn[0].onclick = false;
Then, in your handler, if you want that function to be called, you call it:
clickhandler.call(this, event);
Example:
// Get the button
var btn = $("#btn1");
// Save and remove the onclick handler
var clickHandler = btn[0].onclick;
btn[0].onclick = false;
// Hook up your handler
$("#btn1").click(function(event) {
alert("event triggered");
if (!confirm("Allow it?")) {
// Disallowed, don't call it
alert("stopped it");
} else {
// Allowed, call it
clickHandler.call(this, event);
}
});
// The onclick handler
function clicked() {
alert("clicked me");
}
<form id="form1" onsubmit="return false">
<button id="btn1" onclick="clicked();">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Try event.stopPropagation()
api docs
if condition is true then remove the 'onclick' attribute
if (some_condition == true) {
$("#btn1").removeAttr('onclick').click(function(event) {
alert("event triggered");
//do something
});
}
function clicked() {
alert("clicked me");
}
I am sharing a quick workaround without knowing why you cannot add logic to stop adding "onclick="clicked();" code which you are saying getting automatically added.
I recommend you hide button with id as "btn1". Add style display:none. You donot need on ready function for this but simply add style attribute to the button btn1 or if that is also not possible directly then use jQuery to do that post document ready.
Read :
How to change css display none or block property using Jquery?
Then add a new button to the form using jQuery with id as "btn2" and add register the btn2 click event as well. DO this after form load.
<form id="form1">
<div id="newbut">
<button id="btn1" onclick="clicked();">Submit</button>
</div>
</form>
jQuery("#newbut").html('<button id="btn2">Submit</button>');
$(document).on('click', '#btn2', function(){
// Your Code
});
Refer below url to how to register click event for new button:
Adding click event for a button created dynamically using jQuery
jquery - Click event not working for dynamically created button
Can't you do the condition check and the clicked() logic in one function? i.e
<script>
function clicked() {
if(some_condition == true){
return;
}
alert("clicked me");
}
</script>

Bypass onclick event and after excuting some code resume onclick

I have the below html button which have onclick event
<button onclick="alert('button');" type="button">Button</button>
and the following js:
$('button').on('click', function(){
alert('jquery');
});
After executing some js code by jQuery/Javascript, i want to continue with the button onclick handler e.g: jquery alert first and than button alert.
i tried so many things like "remove attr and append it after executing my code and trigger click (it stuck in loop, we know why :) )" and "off" click. but no luck.
is it possible via jQuery/javascript?
any suggestion much appreciated
Thanks
A little bit tricky. http://jsfiddle.net/tarabyte/t4eAL/
$(function() {
var button = $('#button'),
onclick = button.attr('onclick'); //get onclick value;
onclick = new Function(onclick); //manually convert it to a function (unsafe)
button.attr('onclick', null); //clear onclick
button.click(function() { //bind your own handler
alert('jquery');
onclick.call(this); //call original function
})
});
Though there is a better way to pass params. You can use data attributes.
<button data-param="<%= paramValue %>"...
You can do it this way:
http://jsfiddle.net/8a2FE/
<button type="button" data-jspval="anything">Button</button>
$('button').on('click', function () {
var $this = $(this), //store this so we only need to get it once
dataVal = $this.data('jspval'); //get the value from the data attribute
//this bit will fire from the second click and each additional click
if ($this.hasClass('fired')) {
alert('jquery'+ dataVal);
}
//this will fire on the first click only
else {
alert('button');
$this.addClass('fired'); //this is what will add the class to stop this bit running again
}
});
Create a separate javascript function that contains what you want to do when the button is clicked (i.e. removing the onclick attribute and adding replacement code in its own function).
Then call that function at the end of
$('button').on('click', function(){
alert('jquery');
});
So you'll be left with something like this
function buttonFunction()
{
//Do stuff here
}
$('button').on('click', function()
{
alert('jquery');
buttonFunction();
});
<button type="button">Button</button>

Changing what function to call depending on which button is pressed

Okay So I what to have 3 buttons
<div id="button1" onclick="choose1()">Button1</div>
<div id="button2" onclick="choose2()">Button2</div>
<div id="button3" onclick="choose3()">Button3</div>
And a start button
<div id="startButton" onclick="noFunction()">Start</div>
I want to make it so that pressing on of the 3 option buttons it changes what function will be called from the start button and the background image of the start button should change.
Is there a way to do this with just javascript or do I need jquery?
It also doesn't seem possible to use onclick on div tags, jquery to do that aswell?
jsFiddle
You can use onclick on <div> tags. But you shouldn't use onclick on any tags. Don't confuse your HTML layout and display with your JavaScript functionality. Bind your click handlers directly in the JS code (note that this solution is using jQuery):
HTML:
<div id="button1">Button1</div>
<div id="button2">Button2</div>
<div id="button3">Button3</div>
<div id="startButton">Start</div>
JS:
function choose1() {
// ...
}
function choose2() {
// ...
}
function choose3() {
// ...
}
$(function() {
$("#button1").click(choose1);
$("#button2").click(choose2);
$("#button3").click(choose3);
});
You can do it in javascript (anything possible with jQuery is possible with plain javascript, since jQuery is written in javascript).
Changing the click handler for the startButton from javascript is very straightforward:
document.getElementById("startButton").onclick = newFunction;
Changing the background image is also pretty simple:
document.getElementById("startButton").style.backgroundImage = "image.png";
Obviously, you should replace newFunction and "image.png" with the function and image you actually want to use respectively.
You can say
function choose1() {
document.getElementById('startButton').onclick = function() {
alert("Button one was originally press");
}
}
jQuery IS javascript. It is just a library of functions/methods that you can call.
To solve your problem, you should write a function that changes the onclick property of your start button, and add the function you write to the onclick of the other buttons.
Like so:
function chooseOne(){
document.getElementById('startButton').onclick="/\*whatever\*/";
}
A technology like what #nbrooks said in the comments that would do this very well is AngularJS
If you give each selector button a class, you can use javascript to interate them and bind a click event. Then you can store in a data property a key which you can lookup in a json object start stores the related action handler and image. Finally in your click handler you can pull these properties and apply them to the start button by setting the onClick handler and background image of the start button.
<div class="startSelector" data-startdataid="1">Button1</div>
<div class="startSelector" data-startdataid="2">Button2</div>
<div class="startSelector" data-startdataid="3">Button3</div>
<div id="startButton">Start</div>
<script>
var startData = {
"1": {
action: function() {
alert("Button 1 was selected");
},
image: "/images/button1.jpg"
},"2": {
action: function() {
alert("Button 2 was selected");
},
image: "/images/button2.jpg"
},"3": {
action: function() {
alert("Button 3 was selected");
},
image: "/images/button3.jpg"
}
}
var changeStartButton = function(e) {
var startDataIndex = e.target.dataset.startdataid
var data = startData[startDataIndex]
document.getElementById("startButton").onclick = data.action
document.getElementById("startButton").style.backgroundImage = data.image
}
items = document.getElementsByClassName("startSelector")
for (var i = 0; i < items.length; i++) {
items[i].addEventListener("click", changeStartButton);
}
</script>
Example
http://jsfiddle.net/Xk8rv/3/

Inline onclick is overriding JQuery click()

A follow on from this question
Edit
JSFiddle code
As you can see if you run the code the button text does not change, the onclick is overriding the click function. If you remove the form id attribute from the function and the onclick attribute from the html tag the code works as expected (in a real scenario no onclick function implies a submit button rather than a button)
End Edit
I had thought that a typo was responsible for JQuery not firing the click() event when an inline event was specified, however I've run into the issue once more. Here's my code and the offending tag
<input id="submit1" type="button" onclick="this.disabled=true; doSubmit();" value="submit">
<script>myfunction('submit1', 'working', myformID)</script>
var myfunction = function(ID , text , formID) {
if(ID) {
var element = document.getElementById(ID);
if(formID) {
var form = document.getElementById(formID);
}
if (element) {
jQuery(element).click( function() {
if(jQuery(this).attr('disabled')) {
return false;
}
jQuery(this).attr('disabled' , 'disabled');
jQuery(this).attr('value' , processingText);
onclick = (jQuery(this).attr('onclick') || jQuery(this).attr('onClick'));
if(form && !onclick) {
jQuery(form).submit();
}
jQuery(this).click();
});
}
}
};
I'm using javascript to create a function which will disable submit buttons while keeping any onclick attribute working in case of a doSubmit, like in this case. In other cases where the form id is set and there isn't an existing onclick I submit the form. Therefore if there is an issue with the html tag I need a general way to fix it with JS.
Many thanks in advance
Your inline handler disables the button: this.disabled=true;
Then jQuery handler checks if it is disabled and returns if so:
if(jQuery(this).attr('disabled')) {
return false;
}
There is, unfortunately, no way to predict the order of event handlers execution for the same event on the same element.
As a quick fix, I can suggest this:
Demo
jQuery(element).click( function() {
if(jQuery(this).attr('disabled-by-jquery')) {
return false;
}
jQuery(this).attr('disabled' , 'disabled');
jQuery(this).attr('disabled-by-jquery' , 'disabled');
jQuery(this).attr('value' , text);
onclick = (jQuery(this).attr('onclick') || jQuery(this).attr('onClick'));
if(form && !onclick) {
jQuery(form).submit();
}
jQuery(this).click();
});

Categories

Resources