How to separate function execution when different buttons are clicked - javascript

I am using JQuery's .click function and I have multiple buttons on my website. Clicking one button will execute every .click function in my HTML document. Is there a way to make one button execute one .click? I have included some code below to illustrate my problem. Clicking the first button called "Click Me!" will execute all the functions in my HTML document. How would I make it so that the button "Click Me!" does not execute every function in my document?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>
My Website
</title>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
</head>
<body>
<button>
Click Me!
</button>
<button onclick="document.body.style.backgroundColor='blue';">
Change BG color
</button>
<script>
$(document).ready(function () {
$("button").click(function(){
$("#d").hide();
});
});
$(document).ready(function () {
$("button").click(function(){
$("#f").fadeToggle(3000);
});
});
</script>
<button>Toggle fade</button>
<div>
<p id="d">Some text here.</p>
</div>
<div>
<p id="f">Some text to fade.</p>
</div>
</body>
</html>
*Update
So I have changed my script to the following:
$(document).ready(function () {
$('#button1').click(function(){
$("#d").hide();
});
});
Nothing happens when I click the button though. Is this the correct syntax? This syntax was used on W3Schools.

If you use $("button"), the click() function you provide will apply to ALL buttons. I would recommend giving your button an id and then use:
$("#myButtonId").click(function(){
$("#d").hide();
});
JQuery selectors are very useful for targeting your elements in the DOM.

Yep. Put an ID or Class on that button so you can select it with more specificity.
<button id="button1">foo</button>
<button id="button2">bar</button>
$('#button1').on('click', function(){ $("#d").hide(); });
$('#button2').on('click', function(){ console.log("button2"); });

You should give the button and ID or class like so:
<button id="myButton">Test</button>
And then use the following click event:
$("#myButton").click(function(){
...
});

Related

Show text after clicking a button

I got this h1 tag that I want change when clicking a button.
I want it so then when you click a button, an h1 tag will change to something else, like to "bananas" or something. How could I use an onclick event to change it?
You can use (addEventListener) with (click) event to listen on click button by using javascript code.
i hope it's clear and helpful, Thanks!.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<!-- My Heading -->
<h1 id="MyHeading">This is a Heading</h1>
<!-- My Button -->
<button id="MyButton">Click Me!</button>
</body>
</html>
<script>
//Select button by id
const MyButton = document.getElementById('MyButton');
//Add on click listener for button
MyButton.addEventListener('click', function() {
//Select (h1) heading by id, and then change it's value to (bananas)
document.getElementById('MyHeading').innerText = "bananas"
})
</script>

Javascript return false and event.target

Could someone explain why the clicking on button1 doesn't get captured? I know return false on event click will stop the propagation, but it should still capture the element by document.addEventListener('click', function(e) {console.log(e.target);}); because we are trying to capture directly the main element via e.target not its parent element.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
return false;
});
});
</script>
</head>
<body>
<button id="button1">Button1 (dont get captured)</button>
<button id="button2">Button2 (get captured)</button>
<script>
document.addEventListener('click', function(e) {
console.log(e.target);});
</script>
</body>
</html>
I can't change that jQuery code $("#button1").click(function(){return false});, but still, want to capture the button1 element when it gets clicked (with javascript), is there any workaround?
i could bind another event handler to button1 like this document.getElementById("button1").addEventListener("click", function(e){console.log(e.target)}); in real there are many many elements which I want to capture (with different classes and id), it would be impractical to add an event listener to each of them, I showed one button just for an example. , I just simply want to log whichever element is clicked.
I can't change the jQuery code or HTML of the page, i want to run some tests in chrome console only, for which i want to capture each element which is clicked
thanks
The return false; prevents the browser from performing the default action for button1 link.
The equivalent code for return false is:
$('.button1')
.click(function (event) {
event.preventDefault();
event.stopPropagation();
});
If you just want to stop propagation use stopPropagation().
Take a look at this, and read more about preventDefault() and stopPropagation()
Not very efficient but worked for me
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
return false;
});
});
</script>
</head>
<body>
<button id="button1">Button1 (dont get captured)</button>
<button id="button2">Button2 (get captured)</button>
<script>
elements = document.querySelectorAll('body *');
elements.forEach(function(elem) {
elem.addEventListener('click', function(e){
console.log(e.target); // or simply console.log(elem)
});
});
</script>
</body>
</html>
Thanks to everyone, especially #mplungjan who gave me this idea

How to use two 'onclick' event

Below is my code, why isn't it working when I click on Appended text ?
1: click on This is a paragraph.
2: click on Appended text
3: Must show Appended item with color red.
$(document).ready(function(){
$(".ali").click(function(){
$(this).parent().append("<b class='reza'>Appended text</b>");
});
$(".reza").click(function(){
$(this).append("<li style='color:red'>Appended item</li>");
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<p><span class="ali"> This is a paragraph. </span> </p>
</body>
</html>
Since the element with class "reza" is not created yet, you need to define click event on future element with "reze" class. Check the below working code.
$(document).ready(function(){
$(".ali").click(function(){
$(this).parent().append("<b class='reza'>Appended text</b>");
});
$("body").on("click",".reza",function(){
$(this).append("<li style='color:red'>Appended item</li>");
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<p><span class="ali"> This is a paragraph. </span> </p>
</body>
</html>
Elements which are dynamically added to the document, can not be issued event listeners by normal means.
This is how you would normally add an event listener in jQuery.
$(element).on('click', function() {
// do something
});
The reason the example above won't work with a dynamically added element is due to the fact that the element doesn't exist when the script gets compiled.
So why does this work?
$(parent).on('click', 'element' function() {
// do something
});
This works because when the file gets compiled, the parent already exists. If you have a reference to the parent, then you can retrieve the children at anytime. Since the DOM is modular.
This question, in one way or another, has already been asked multiple times. Here's the preferred answer.
Event binding on dynamically created elements?

Why doesn't innerHTML work with white spaces?

In the below html, the front button doesn't respond while the back button changes the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="move front">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
In the below, both the buttons change the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="movefront">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
Why does a bank space make a button unresponsive?
That is just invalid HTML.
You have to put quotes around your whole onclick attribute value, otherwise it will end at the space.
onClick = document.getElementById('para').innerHTML="move // cut off here
front" // a second (meaningless) attribute for your button tag.
Please consider this syntax:
<button onclick="document.getElementById('para').innerHTML='move front'">front</button>
You are probably having issues if you are using this technique.
I am sorry but this is not how you attach a click event to elements in modern javascript, at least if you want to work with what's called "good practices".
The better method would be to attach a click event to a desired element using javascript.
I will give you a short code example.
First the HTML - I will use your original HTML (modified a bit):
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button id="frontBtn"> front </button>
<button id="backBtn"> back </button>
</body>
</html>
As you can see, I have removed your "onclick" events from the buttons, and assigned an id to each button.
Second, we will write some javascript to properly attach a click event to each one of the buttons, and of course execute the change of text as you originally was intending to do:
if you are familiar with jQuery then this will do:
$('#frontBtn').on('click',function(){
$('#para').html('move front');
});
$('#backBtn').on('click',function(){
$('#para').html('back');
});
This can also be done with vanilla (native) javascript:
document.getElementById("frontBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "move front";
});
document.getElementById("backBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "back";
});
Now we have a nicely structured event handler for each button, more code can be easily added.
As for where to insert your javascript ?
You can add the javascript to your html document by using script tags in your html document head like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// your code here..
</script>
</head>
<body>
....
....
Or even better - create a separate script file and load it at the bottom of your html page like this:
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
....
....
<script type="text/javascript" src="scripts.js"></script>
</body>
</html>
This is the better way to attach events to elements, using javascript.
Imagine if you try to write 50-100 lines of code inline ? impossible! but with an event handler function you can do it easily.
Things will basically work better and your project will be much easier for you to maintain.
Hope it helps a bit!

Need to determine button clicked in a JQuery mobile popup and perform actions based thereon

I am having a problem with a JQM popup. The popup has 3 buttons, and the action taken in the main program depends on which button is clicked. The code in the main program is run more than once and I am not sure why.
The simple example below uses an alert to display which button on the popup was clicked. When the popup is called the first time, it works as hoped, the 2nd time, the alert is displayed twice, the 3rd time, the alert is displayed 3 times, etc.
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css" />
<script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"/></script>
<script type="text/javascript" src="js/jquery.mobile-1.3.2.min.js"></script>
<script>
function doCustomDialog(text1,button1,button2,button3,callback)
{
$("#customDialog .customDialogDesc").text(text1);
$("#customDialog .customDialogOption1").text(button1).on("click.customDialog", function(){
callback("option1");
});
$("#customDialog .customDialogOption2").text(button2).on("click.customDialog", function(){
callback("option2");
});
$("#customDialog .customDialogOption3").text(button3).on("click.customDialog", function(){
callback("option3");
});
$("#customDialog").popup("open");
}
</script>
</head>
<body>
<div data-role="page" id="mainPage">
<div data-role="content">
<INPUT type="button" id="confirm" value="Save data" />
<div data-role="popup" id="customDialog" data-title="Are you sure?" class="ui-content">
<p class ="customDialogDesc">???</p>
Yes
No
Cancel
</div>
</div>
</div>
<script>
$("#mainPage").on("pageshow", function(e) {
$("#confirm").click(function() {
doCustomDialog("A similar record already exists. Do you want to Update the existing record or Add a new record?", "Update", "Add", "Cancel",
function( returned )
{
//Do things depending on the button clicked, for now just display which button was clicked
alert(returned);
});
});
});
</script>
</body>
</html>
Use popupafterclose to unbind any attached click event. Also, note the direct parent of data-role=popup should be data-role=page.
$(document).on("popupafterclose", "#customDialog", function () {
$('#customDialog a').off('click');
});
Demo
Note: To change button's text, use .ui-btn-inner selector i.e. $("#customDialog .customDialogOption1 .ui-btn-inner").text(button1) in order not to lose button style.
Update: If you wish to go with the above note, you then need to unbind click .ui-btn-inner i.e. $('#customDialog a .ui-btn-inner').off('click');
The issue is because you are attaching another event to each button for every successive time the popup is opened. You can prevent this by using one() to attach the events:
$("#customDialog .customDialogOption1").text(button1).one("click.customDialog", function(){
callback("option1");
});
$("#customDialog .customDialogOption2").text(button2).one("click.customDialog", function(){
callback("option2");
});
$("#customDialog .customDialogOption3").text(button3).one("click.customDialog", function(){
callback("option3");
});
Alternatively, you could remove all the events attached to the buttons first by adding the following line at the start of your doCustomDialog function:
$("#customDialog a").off();
Then you can re-attach then using on as you currently do.

Categories

Resources