Html Button That Takes to a Page Then Press Again and to Another Page

HTML Button onclick – JavaScript Click Event Tutorial

Whenever you visit a website, yous'll probably click on something like a link or button.

Links take you to a certain office of the page, some other page of the website, or another website entirely. Buttons, on the other mitt, are usually manipulated by JavaScript events so they can trigger certain functionality.

In this tutorial, we are going to explore the 2 different ways of executing click events in JavaScript using two different methods.

Beginning, nosotros'll expect at the traditional onclick style that you do right from the HTML page. And so we'll see how the more modern "click" eventListner works, which lets you lot dissever the HTML from the JavaScript.

How to Employ the onclick event in JavaScript

The onclick event executes a sure functionality when a button is clicked. This could be when a user submits a course, when y'all modify certain content on the web page, and other things similar that.

You place the JavaScript role you want to execute inside the opening tag of the button.

Basic onclick syntax

                <element onclick="functionToExecute()">Click</element>                              

For instance

                <button onclick="functionToExecute()">Click</button>                              

Note that the onclick aspect is purely JavaScript. The value it takes, which is the role you desire to execute, says it all, as it is invoked right within the opening tag.

In JavaScript, you lot invoke a function by calling its name, then you lot put a parenthesis subsequently the role identifier (the name).

onclick effect example

I accept prepared some basic HTML with a little bit of styling and so we can put the onclick event into real-globe practise.

                <div>   <p form="name">freeCodeCamp</p>   <button>Change to Blue</button> </div>                              

And here's the CSS to make information technology await skillful, forth with all the residue of the example code:

                                  body {    display: flex;    align-items: centre;    justify-content: center;    peak: 100vh;       } p {    font-size: 2rem; }  push {     padding: 7px;     edge: none;     border-radius: 4px;     cursor: pointer; }  button.blue {     background-color: #3498db; }  button.green {     background-color: #2ecc71; }  button.orange {    groundwork-color: orangered; }                              

So, on the web folio, this is what nosotros have:
changeColor

Our aim is to modify the color of the text to blue when we click the button. So nosotros need to add an onclick attribute to our push, so write the JavaScript function to alter the colour.

So we demand to make a slight change in our HTML:

                <div>   <p grade="name">freeCodeCamp</p>   <button onclick="changeColor()">Change to Blue</button> </div>                              

The function we desire to execute is changeColor(). Then we demand to write it in a JavaScript file, or in the HTML file within a <script> tag.

If you lot want to write your script in a JavaScript file, you need to link it in the HTML using the syntax below:

                <script src="path-to-javascript-file"></script>                              

If you desire to write the script in an HTML file, simply put it inside the script tag:

                <script>   // Your Scripts </script>                              

Now, let's write our changeColor() office.

First of all, we need to select the element we want to dispense, which is the freeCodeCamp text inside the <p> tag.

In JavaScript, you lot do that with the DOM's getElementById(), getElementsByClassName(), or the querySelector() methods. And so you store the value in a variable.

In this tutorial, I will be using querySelector() because it is more modern and it's faster. I will besides be using const to declare our variables instead of let and var, considering with const, things are safer as the variable becomes read-only.

                const name = document.querySelector(".proper name");                              

Now that we have the text selected, let'southward write our function. In JavaScript, the bones function syntax looks similar this:

                function funcctionName () {     // What to do }                              

So let'due south write our function:

                function changeColor() {     proper noun.style.colour = "blue"; }                              

What's going on?

Recall from the HTML that changeColor() is the office we are going to execute. That'southward why our function identifier (name) is set to changeColor. If the proper 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 change anything that relates to mode, y'all need to write "style" then a dot (.). This is followed past what y'all want to change, which might be the color, groundwork colour, font size, and so on.

So, inside our function, we take the name variable we declared to get our freeCodeCamp text, then nosotros alter the color to blue.

The color of our the text turns bluish any fourth dimension the button is clicked:

changeColor

Our code is working!

We could take things a footling scrap farther past irresolute our text to be more colors:

                <div>       <p class="name">freeCodeCamp</p>       <push button onclick="changeColor('bluish')" class="blue">Blue</push button>       <button onclick="changeColor('green')" class="green">Green</button>       <push onclick="changeColor('orangered')" grade="orange">Orangish</button> </div>                              

Then, what we want to exercise is modify the text to blueish, green, and orange-cerise.

This fourth dimension effectually, the onclick functions in our HTML take the values of the colour nosotros desire to change the text to. These are called parameters in JavaScript. The function we'll write takes its own too, which we will call "color".

Our web folio changed a little:

changeColors

So, let's select our freeCodeCamp text and write the function to modify its color to blue, green, and orangish-red:

                const proper name = document.querySelector(".name");  function changeColor(colour) {    name.fashion.color = color; }                              

The block of code in the role takes the proper name variable (where nosotros stored our freeCodeCamp text), and then set the color to whatever we passed into the changeColor() functions in the HTML buttons.
changeColors

How to Use the click eventListener in JavaScript

In JavaScript, in that location are multiple ways of doing the same thing. Equally JavaScript itself evolved over time, we started needing to separate the HTML, CSS, and JavaScript code in gild to comply with best practices.

Event listeners brand this possible as they permit you separate the JavaScript from the HTML. Y'all can also do this with onclick, but lets take another approach here.

Basic eventListener syntax

                                  element.addEventListener("type-of-issue", functionToExecute)                              

Now, let'southward change the freeCodeCampt text to bluish by using the click eventListner

This is our new HTML:

                                  <div>       <p course="name">freeCodeCamp</p>       <push>Modify Color</push>  </div>                              

And this is what information technology looks like:

colorChange

This time around in our script, we need to select the button likewise (not just the freeCodeCamp text). That'due south because in that location'southward zippo JavaScript in the opening tag of our push, which is cool.

And so, our script looks like this:

                const name = document.querySelector(".name"); const btn = document.querySelector("button");        btn.addEventListener("click", function () {         name.style.color = "blueish";  });                              

We tin can as well divide our function totally from the eventListener and our functionality will still remain the same:

                btn.addEventListener("click", changeColor);       function changeColor() {         name.way.color = "blue"; }                              

changeColorWithEvents

How to Build a " Show More" and "Bear witness Less" Push with JavaScrpit

I of the best ways to acquire is past making projects, so allow'south take what we've learned almost the onclick and "click" eventListner to do build something.

When you visit a blog, you often run across excerpts of manufactures first. Then yous tin click on a "read more" push to bear witness the rest. Let'southward try to exercise that.

This is the HTML we are dealing with:

                                  <commodity id="content">       <p>         freeCodeCamp is one of the all-time platforms to acquire how to code.         freeCodeCamp has a detailed curriculum that will take you from nada to         hero in spider web development, software engineering, auto learning, and         more than.       </p>        <p>         freeCodeCamp also has a YouTube aqueduct containing over 1000 videos on         web evolution, software engineering, car learning, data science,         freelance web evolution, database administration, and pretty much         annihilation related to tech. To get updates when videos are uploaded, you lot         demand to subscribe to the channel and plow on notifications. You can too         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         earth in order to pay employees and maintain servers. If y'all are         generous plenty consider joining the donors.       </p>     </commodity>  <push onclick="showMore()">Bear witness more</button>                              

Information technology'due south simple HTML with some facts well-nigh freeCodeCamp. And there's a push button we already attach an onclick to. The function we desire to execute is showMore(), which nosotros will write soon.

Without a CSS, this is what we accept:
articleunstyled

It'south not super ugly, simply we can make information technology look better and act the fashion nosotros want it to. So we have some CSS which I will explain beneath:

                <style>       * {         margin: 0;         padding: 0;         box-sizing: border-box;       }        body {         groundwork: #f1f1f1;         display: flex;         marshal-items: center;         justify-content: centre;         flex-management: column;       }        article {         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-tiptop: 1000px;       }        button {         groundwork: #0e0b22;         colour: #fff;         padding: 0.6rem;         margin-peak: 20px;         border: none;         edge-radius: 4px;       }        button:hover {         cursor: pointer;         background: #1e1d25;       } </fashion>                              

What's the CSS doing?

With the universal selector (*), we are removing the default margin and padding assigned to elements so nosotros tin can add our own margin and padding.

Nosotros also have box sizing set to border-box and then we tin include the padding and border in our elements' total width and height.

We centered everything in the body with Flexbox and gave it a light grey background.

Our <article> element, which contains the text, has a width of 400px, a white groundwork (#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 information technology have a font-size of 18px, and then we gave them a maximum height of 270px. Due to the max height of the article element, all the text won't exist independent and volition overflow. To fix this, we set overflow to subconscious in order not to prove that text at first.

The transition holding ensures that every change happens later on 1 second. All text inside the article are justified and have a margin top of 20 pixels so it doesn't stay likewise attached to the tiptop of the folio.

Because we removed the default margin, our paragraphs got all pushed together. Then we set up a bottom margin of 16 pixels in club to separate them from one some other.

Our selector, commodity.open, has a property of max-summit set up to 1000px. This means that whatsoever time the article element has a course of open attached to information technology, the maximum height will change from 270px to 1000px to show the rest of the commodity. This is possible with JavaScript – our game changer.

Nosotros styled our button with a darkish background and made it white. We fix its border to none to remove HTML's default border on buttons, and we gave it a edge radius of 4px so it has a slightly rounded edge.

Finally, we used the hover pseudo-form 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 go – that's the CSS.

Our page at present looks improve:

articlestyled

The next matter we need to do is to write our JavaScript and then we can meet the rest of the commodity that is hidden.

We accept an onclick attribute inside our push opening tag prepare to execute a showMore() office, so let'south write the function.

We need to select our article showtime, considering we take to bear witness the rest of information technology:

                const article = document.querySelector("#content");                              

The side by side thing we demand to exercise is write the function showMore() then we can toggle betwixt seeing the residual of the article and hiding it.

                office showMore() {      if (article.className == "open") {        // read less        article.className = "";        button.innerHTML = "Show more";      } else {        //read more than        article.className = "open";        button.innerHTML = "Show less";      }   }                              

What is the function doing?

We use an if…else statement hither. This is a crucial part of JavaScript that helps y'all make decisions in your code if a certain condition is met.

The basic syntax looks like this:

                if (condition == "something") {   // Practise something } else {   // Practise something else }                              

Here, if the class name of the commodity equals open (that is, nosotros desire to add the course of open to it, which was set to a maximum height of 1000px in the CSS), then we want to see the residuum of the article. Else, we want the article to return to the initial state where a part of it is hidden.

We practise this past assigning it a class of open in the else block, which makes it show the rest of the commodity. Then we set the class to an empty cord (none) in the if block, which makes information technology return to the initial country.

Our lawmaking is working fine with a smooth transition:
article

We can separate the HTML and JavaScript and however use onclick, considering onclick is JavaScript. So information technology's possible to write this in a JavaScript file instead of starting from the HTML.

                                  push button.onclick = function () {      if (commodity.className == "open") {        // read less        article.className = "";        button.innerHTML = "Show more";      } else {        //read more        article.className = "open";        push.innerHTML = "Bear witness less";      }   };                              

articleonclick

We can also exercise this using an eventListner:

                <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 zippo to         hero in web development, software engineering, machine learning, and         many more.       </p>        <p>         freeCodeCamp too has a YouTube aqueduct containing over m videos on         spider web development, software engineering, machine learning, data scientific discipline,         freelance web development, database administration, and pretty more than         anything related to tech. To get updates when videos are uploaded, you         demand to subscribe to the channel and turn on notifications. You can too         follow freeCodeCamp on Twitter, where links to well written articles and         videos are tweeted daily.       </p>        <p>         Since no i has to pay to acquire how to lawmaking on freeCodeCamp,         freeCodeCamp runs on voluntary donations from donors all around the         world in guild to pay employees and maintain servers. If you are         generous plenty consider joining the donors.       </p> </article>  <button id="read-more">Show more</button>                              
                                  const article = document.querySelector("#content");  const button = document.querySelector("#read-more");  button.addEventListener("click", readMore);  function readMore() {      if (article.className == "open") {        // Read less      commodity.className = "";      button.innerHTML = "Show more";    } else {      article.className = "open";      button.innerHTML = "Testify less";    } }                              

Our functionality remains the aforementioned!

Decision

I hope this tutorial helps you understand how the click issue works in JavaScript. Nosotros explored ii different methods here, so at present y'all can first using them in your coding projects.

Cheers for reading, and go on coding.



Learn to code for free. freeCodeCamp'due south open source curriculum has helped more than than 40,000 people get jobs as developers. Get started

schaefernouse1990.blogspot.com

Source: https://www.freecodecamp.org/news/html-button-onclick-javascript-click-event-tutorial/

0 Response to "Html Button That Takes to a Page Then Press Again and to Another Page"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel