Show text after clicking a button - javascript

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>

Related

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!

All of the elements change on Click, not just the targeted one

I am just playing with some basic Jquery and something strange is happening. I have two elements on the page.. an h1 heading, and a generic link. When I click the link I would like the text to change to "This text has now changed", and it does, but then either the button disappears and a new h1 is created with the same "this text has not changed" text, or the button itself turns into the h1. I'm not sure, but here's my code:
HTML:
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<h1>This element should change.<h1>
Click Me<br>
</body>
</html>
JQUERY:
$(document).ready(function() {
$(".myLink").click(function() { // this is a convenience method that targets the same elements above just in a quicker fashion.
$("h1").html("This text has now changed.");
});
});
Picture Before the click:
Picture After:
Also, when I added the fade out method everything disappears once again, not just the targeted "h1" element.
Any advice is greatly appreciated as always. Thank you.
You have two opening <h1> tags (the second one is missing a /.)
<h1>This element should change.<h1>
^here
It looks like you have two start tags. EG:
<h1>Heading 1<h1>
Try changing the second tag to an end tag. EG:
<h1>Heading 1</h1>
^
Your h1 tag is not closed. You have 2 opening tags, and by default, your link is contained by the second opening tag so it's changing that html

How to separate function execution when different buttons are clicked

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(){
...
});

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.

Using jquery click event inside an editable div

I use JQuery to register events for different tags. Here is the code so far:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.7.js"></script>
</head>
<body>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<div><p>another one</p></div>
<p><strong>big one</strong></p>
<div contentEditable="true"><p>hello <b>there</b></p></div>
<script>
$("p").click(function () {
alert('p tag');
});
$("div").click(function () {
alert('div tag');
});
$("b").click(function () {
alert('strong tag');
});
</script>
</body>
</html>
I want to develop a simple text editor and want to capture click events so that I can update the state of my buttons (bold, italics, ...). I want the click events to work inside an editable div as well but they only fire once when the div tag is selected and afterwards when the editing begins, clicking anywhere inside that div doesn't fire, even though I have p and b tags inside the div. Is is possible to achieve this using an editable div? Basically I want to be able to know if the cursor is inside a b tag or an i tag so that I can update the state of my buttons.
you can use .one
$("editableDIV").one("click",function(){...});

Categories

Resources