How to Check if User Clicks Button Again
Whenever yous visit a website, you'll probably click on something like a link or button.
Links take yous to a certain role of the page, another page of the website, or some other website entirely. Buttons, on the other hand, are usually manipulated by JavaScript events so they tin can trigger sure functionality.
In this tutorial, we are going to explore the two different ways of executing click events in JavaScript using two unlike methods.
First, we'll await at the traditional onclick style that you practice right from the HTML page. So we'll run across how the more modern "click" eventListner works, which lets you separate the HTML from the JavaScript.
How to Use the onclick event in JavaScript
The onclick event executes a certain functionality when a push button is clicked. This could be when a user submits a form, when you alter certain content on the web page, and other things like that.
You place the JavaScript office you desire to execute inside the opening tag of the button.
Basic onclick syntax
<element onclick="functionToExecute()">Click</chemical element> For instance
<push onclick="functionToExecute()">Click</push button> Note that the onclick attribute is purely JavaScript. The value information technology takes, which is the role you lot desire to execute, says it all, as information technology is invoked right within the opening tag.
In JavaScript, you invoke a function by calling its name, and so you put a parenthesis later the function identifier (the proper name).
onclick event example
I accept prepared some basic HTML with a footling bit of styling so nosotros tin put the onclick event into existent-earth practice.
<div> <p class="proper noun">freeCodeCamp</p> <button>Alter to Blue</button> </div> And hither'due south the CSS to make it expect good, along with all the residuum of the example code:
body { display: flex; align-items: eye; justify-content: middle; acme: 100vh; } p { font-size: 2rem; } push button { padding: 7px; border: none; edge-radius: 4px; cursor: pointer; } button.bluish { background-color: #3498db; } button.greenish { groundwork-color: #2ecc71; } button.orange { background-color: orangered; } So, on the spider web folio, this is what nosotros have:
Our aim is to change the color of the text to blue when we click the button. So nosotros demand to add together an onclick aspect to our button, then write the JavaScript role to modify the color.
So nosotros demand to make a slight change in our HTML:
<div> <p class="name">freeCodeCamp</p> <button onclick="changeColor()">Change to Blueish</push button> </div> The function nosotros want to execute is changeColor(). So we demand to write it in a JavaScript file, or in the HTML file inside a <script> tag.
If you lot want to write your script in a JavaScript file, you demand to link it in the HTML using the syntax below:
<script src="path-to-javascript-file"></script> If yous want to write the script in an HTML file, just put it inside the script tag:
<script> // Your Scripts </script> At present, permit'due south write our changeColor() function.
Offset of all, we demand to select the element we desire to dispense, which is the freeCodeCamp text within the <p> tag.
In JavaScript, you do that with the DOM's getElementById(), getElementsByClassName(), or the querySelector() methods. Then you store the value in a variable.
In this tutorial, I will exist using querySelector() because it is more modern and it'due south faster. I will as well be using const to declare our variables instead of let and var, because with const, things are safer every bit the variable becomes read-merely.
const name = document.querySelector(".name"); Now that nosotros have the text selected, let's write our function. In JavaScript, the basic function syntax looks similar this:
part funcctionName () { // What to practise } So let's write our function:
function changeColor() { name.style.color = "blue"; } What's going on?
Call back from the HTML that changeColor() is the function we are going to execute. That'south why our function identifier (name) is set to changeColor. If the name doesn't correlate with what's in the HTML, it won't work.
In the DOM (Document Object Model, refers to all of the HTML), to alter anything that relates to style, you demand to write "fashion" then a dot (.). This is followed by what you want to modify, which might exist the color, background color, font size, and so on.
So, within our function, we take the proper name variable nosotros declared to get our freeCodeCamp text, then we change the color to blue.
The colour of our the text turns blue any fourth dimension the push button is clicked:
Our code is working!
We could take things a little chip farther by changing our text to be more colors:
<div> <p form="name">freeCodeCamp</p> <push onclick="changeColor('bluish')" class="blue">Blue</push button> <button onclick="changeColor('light-green')" grade="green">Dark-green</push button> <button onclick="changeColor('orangered')" grade="orange">Orange</button> </div> So, what we desire to do is change the text to blue, green, and orangish-ruddy.
This fourth dimension effectually, the onclick functions in our HTML take the values of the color we desire to modify the text to. These are called parameters in JavaScript. The function nosotros'll write takes its own too, which nosotros volition call "color".
Our spider web page inverse a niggling:
So, let's select our freeCodeCamp text and write the office to change its color to bluish, green, and orange-scarlet:
const name = certificate.querySelector(".name"); function changeColor(color) { name.style.color = color; } The block of lawmaking in the office takes the name variable (where we stored our freeCodeCamp text), and so set the colour to any we passed into the changeColor() functions in the HTML buttons.
How to Use the click eventListener in JavaScript
In JavaScript, at that place are multiple ways of doing the same affair. As JavaScript itself evolved over fourth dimension, nosotros started needing to separate the HTML, CSS, and JavaScript code in order to comply with best practices.
Event listeners make this possible equally they let you carve up the JavaScript from the HTML. Yous can also do this with onclick, but lets take some other arroyo here.
Bones eventListener syntax
chemical element.addEventListener("type-of-issue", functionToExecute) Now, let's modify the freeCodeCampt text to blue by using the click eventListner
This is our new HTML:
<div> <p class="name">freeCodeCamp</p> <push>Change Colour</push> </div> And this is what it looks like:
This time around in our script, nosotros need to select the push likewise (not merely the freeCodeCamp text). That's because there's nothing JavaScript in the opening tag of our button, which is cool.
So, our script looks like this:
const name = document.querySelector(".proper noun"); const btn = document.querySelector("button"); btn.addEventListener("click", function () { name.mode.color = "blue"; }); We can also separate our function totally from the eventListener and our functionality will however remain the same:
btn.addEventListener("click", changeColor); function changeColor() { name.style.color = "blueish"; }
How to Build a " Prove More" and "Evidence Less" Button with JavaScrpit
I of the best ways to learn is by making projects, so permit'southward accept what we've learned most the onclick and "click" eventListner to do build something.
When you visit a blog, you often see excerpts of articles outset. Then you can click on a "read more" push button to evidence the rest. Let's endeavor to practise that.
This is the HTML we are dealing with:
<article id="content"> <p> freeCodeCamp is one of the all-time platforms to learn how to code. freeCodeCamp has a detailed curriculum that will take you from zilch to hero in web development, software engineering, car learning, and more. </p> <p> freeCodeCamp also has a YouTube channel containing over thousand videos on web development, software engineering, machine learning, data scientific discipline, freelance web development, database assistants, and pretty much annihilation related to tech. To become updates when videos are uploaded, you need to subscribe to the channel and plow on notifications. You tin too follow freeCodeCamp on Twitter, where links to well written articles and videos are tweeted daily. </p> <p> Since no 1 has to pay to learn how to code on freeCodeCamp, freeCodeCamp runs on voluntary donations from donors all effectually the globe in social club to pay employees and maintain servers. If you are generous enough consider joining the donors. </p> </commodity> <button onclick="showMore()">Testify more</button> Information technology's simple HTML with some facts about freeCodeCamp. And there'south a push we already attach an onclick to. The part we desire to execute is showMore(), which we will write soon.
Without a CSS, this is what we have:
It's not super ugly, simply we tin can arrive look better and human action the way we desire information technology to. So we have some CSS which I will explain below:
<style> * { margin: 0; padding: 0; box-sizing: edge-box; } trunk { groundwork: #f1f1f1; display: flex; marshal-items: center; justify-content: heart; flex-direction: column; } commodity { width: 400px; background: #fff; padding: 20px 20px 0; font-size: 18px; max-height: 270px; overflow: hidden; transition: max-height 1s; text-align: justify; margin-top: 20px; } p { margin-bottom: 16px; } article.open { max-height: 1000px; } push button { background: #0e0b22; color: #fff; padding: 0.6rem; margin-pinnacle: 20px; border: none; border-radius: 4px; } button:hover { cursor: pointer; groundwork: #1e1d25; } </style> What'southward the CSS doing?
With the universal selector (*), we are removing the default margin and padding assigned to elements then nosotros can add our own margin and padding.
We besides have box sizing set to border-box so we tin can include the padding and border in our elements' full width and meridian.
Nosotros centered everything in the torso with Flexbox and gave it a light grey background.
Our <commodity> element, which contains the text, has a width of 400px, a white background (#fff), and has a padding of 20px at the top, 20 on the left and right, and 0 at the bottom.
The paragraph tags inside of it have a font-size of 18px, and then we gave them a maximum peak of 270px. Due to the max elevation of the article chemical element, all the text won't be contained and will overflow. To fix this, we ready overflow to subconscious in guild non to show that text at first.
The transition holding ensures that every alter happens after ane second. All text inside the article are justified and have a margin summit of 20 pixels so it doesn't stay also attached to the top of the page.
Considering we removed the default margin, our paragraphs got all pushed together. So we ready a bottom margin of sixteen pixels in order to separate them from one another.
Our selector, article.open, has a holding of max-tiptop set to 1000px. This means that any time the article element has a class of open attached to it, the maximum elevation will change from 270px to 1000px to show the rest of the article. This is possible with JavaScript – our game changer.
Nosotros styled our button with a darkish groundwork and made information technology white. We set its border to none to remove HTML's default border on buttons, and we gave it a border radius of 4px so it has a slightly rounded edge.
Finally, nosotros used the hover pseudo-class in CSS to change the button cursor to a pointer. The background colour slightly changes when a user hovers their cursor over it.
There we get – that's the CSS.
Our page now looks ameliorate:
The side by side affair we demand to practice is to write our JavaScript so we can see the rest of the commodity that is subconscious.
We take an onclick attribute inside our button opening tag ready to execute a showMore() office, so permit'south write the function.
We need to select our commodity kickoff, because we accept to evidence the rest of information technology:
const article = document.querySelector("#content"); The next thing nosotros need to do is write the function showMore() so we tin can toggle betwixt seeing the rest of the article and hiding it.
part showMore() { if (article.className == "open") { // read less article.className = ""; button.innerHTML = "Evidence more"; } else { //read more than article.className = "open"; button.innerHTML = "Testify less"; } } What is the part doing?
We use an if…else statement here. This is a crucial function of JavaScript that helps yous make decisions in your code if a sure status is met.
The bones syntax looks similar this:
if (condition == "something") { // Do something } else { // Do something else } Hither, if the grade name of the article equals open (that is, we want to add the class of open to it, which was prepare to a maximum acme of 1000px in the CSS), then we want to see the residual of the article. Else, we want the commodity to return to the initial state where a part of it is hidden.
We do this by assigning it a class of open in the else block, which makes it show the rest of the article. And then we gear up the course to an empty string (none) in the if block, which makes it render to the initial state.
Our lawmaking is working fine with a shine transition:
We can split up the HTML and JavaScript and however use onclick, because onclick is JavaScript. And then it'southward possible to write this in a JavaScript file instead of starting from the HTML.
button.onclick = function () { if (article.className == "open") { // read less article.className = ""; button.innerHTML = "Prove more"; } else { //read more article.className = "open"; push.innerHTML = "Evidence less"; } };
We tin also do this using an eventListner:
<commodity id="content"> <p> freeCodeCamp is one of the all-time platforms to larn how to code. freeCodeCamp has a detailed curriculum that will accept you from nix to hero in spider web development, software technology, auto learning, and many more. </p> <p> freeCodeCamp also has a YouTube channel containing over chiliad videos on web development, software engineering, motorcar learning, data science, freelance web development, database assistants, and pretty more anything related to tech. To go updates when videos are uploaded, y'all need to subscribe to the channel and turn on notifications. You lot tin can also follow freeCodeCamp on Twitter, where links to well written articles and videos are tweeted daily. </p> <p> Since no one has to pay to learn how to code on freeCodeCamp, freeCodeCamp runs on voluntary donations from donors all around the world in society to pay employees and maintain servers. If you lot are generous enough consider joining the donors. </p> </article> <button id="read-more">Show more</button> const commodity = document.querySelector("#content"); const button = document.querySelector("#read-more"); button.addEventListener("click", readMore); office readMore() { if (article.className == "open") { // Read less commodity.className = ""; push.innerHTML = "Testify more"; } else { commodity.className = "open"; push.innerHTML = "Prove less"; } } Our functionality remains the same!
Conclusion
I hope this tutorial helps you sympathise how the click event works in JavaScript. We explored two unlike methods here, so now you can start using them in your coding projects.
Thanks for reading, and proceed coding.
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people become jobs as developers. Go started
Source: https://www.freecodecamp.org/news/html-button-onclick-javascript-click-event-tutorial/
0 Response to "How to Check if User Clicks Button Again"
Post a Comment