Skip to content Skip to sidebar Skip to footer

Click on Something to Add Class Then Click Again to Remove Vanilla Javascript

Specifically, we're going to see how nosotros can allow our file to allow our application here to requite u.s. the ability to add together or remove classes just past clicking on i of the elements. And so I'one thousand going to start off hither by creating a basic HTML page and then I'm going to create some divs. So I'm going to accept a div here and this is going to have an ID of mainHeading and and so it'southward going to have a course of activeHeading.

And so we're going to inside of this div place some content and information technology can simply be something super basic like How-do-you-do there and on the right-hand side hither I take the aforementioned file open so if I hit refresh you lot tin see it says How-do-you-do there.

large

Non really anything as well exciting so let's add a few styles so I'm gonna come into the head tag here and create a few styles it's not going to be anything also crazy simply just enough for us to exist able to add and remove styles and to be able to visually come across the difference. So I'chiliad going to create a course like nosotros have in that location in our div of activeHeading and inside of this, I'll add a color, so let's go with firebrick and then font size and for the font size I'thou going to go with 2em so information technology's to be double the normal size which will requite us kind of a heading and then after that I just want to have a cursor and get in a arrow. So now if I hit save and come over here and hit refresh y'all tin can see nosotros have selected this chemical element and when I hover over it is now a cursor information technology has the colour and the font size.

large

Now I as well want to be able to have a non-agile heading and then I'm going to and actually let me just re-create everything here because it has got a few similarities and then a few key differences. So this 1 I'm going to say nonActiveHeading and for the colour instead of firebrick let'south go with something quite a bit different like cornflowerblue. And then for the font size, nosotros'll brand this for 4em so this is going to exist quite a bit larger and volition keep that arrow. If I come up over here and switch this to be nonActiveHeading.

We can run across what this class will look like then if I hit refresh you can see that information technology is working properly.

large

and so right now we accept our 2 classes and then we have our HTML div which is inside of the document object model but right at present if nosotros want to change how this div looks we need to hardcode this value in. And so what nosotros're going to walk through is how we can leverage javascript to be able to alter this form simply based on clicking the element right in that location.

And so I'm going to come up down beneath the body tag hither and create a script tag and this is where we're going to identify all of our Javascript. So hither I'll say const heading. And now let's run our query and if y'all're ever curious on how to run the query you can come up to the javascript console and y'all can say something like certificate and then go with your query in the concluding guide we used to get elements by class ID but right now I'1000 going to for the sake of sit-in. I'm only using a regular ID then I tin can meet a certificate become ElementById and then pass in the name of the element. Then right hither that's going to be mainHeading and if I run that you tin can run into that that brings our div.

large

So this is working properly then I can but take this exact code right here and I can use this and gear up this inside of the variable. So now I take a const heading so we accept a variable called Heading and information technology is bringing in that values so it'due south bringing in that entire div. So now what I want to do is I want to set up what is called a click handler and and then because we're wanting to handle a click that is the best choice right here. And then I want to capture every time that this is clicked and I want to perform some activeness.

In that location are a number of means of doing that, we're going to walk through them in subsequent videos. But for right now I'g going to simply call this chemical element that nosotros've selected which is that div element and then I'm gonna say on click and so equally you can see there are a number of values whenever you just blazon on if you have the autocomplete IntelliSense from any your text editor is.

large

Y'all can have onboard, onactivate, on all kinds of things. Right now I just want to have onclick and what onclick does is you pass it a function and then let's give ourselves a picayune flake more room here so it can be in the center of the page. And and then for onclick I'chiliad going to store or pass in a function, so I'm gonna say equals then I'1000 gonna use an arrow office hither so I don't want to pass in any parameters and then use the arrow syntax and so now we have our onclick.

large

What this means because this may look a petty bit weird also if you lot've never seen it before but all that we're saying correct hither is that we've selected the heading and then whatever time that that heading is clicked. I desire you to practice everything within of here so we're passing in a code block and so whatever set of processes we want to have place. We want that to happen whenever something is clicked whenever this heading is clicked. In this case, you outset off with the conditional, and even earlier I get there allow's actually test this to make certain that this is working. So allow's not get besides far ahead of ourselves and then I'm going to say console log and say I was clicked. hit salvage and at present if you come and striking refresh here to clear this out and if I click on this you tin see that that is working. Every fourth dimension I click on it says I was clicked.

large

So our click handler and our query are working properly.

So the other thing that nosotros could do here is we could add a provisional. And then I'm going to say if the heading and then I can become the class list. And so if y'all are just curious on how I'm doing this all y'all have to practice is run the verbal same code that nosotros had right here. So if you recollect we typed document.getElementById('mainHeading') but similar this and that gave united states exactly what we wanted. We could store information technology in a variable called Heading if we want to. Then I could say const heading and really, headings are even alleged considering we take it right here. So let'south just call it headingTwo merely to make it like shooting fish in a barrel.

So headingTwo and and so now, if you want to see what's bachelor for headingTwo, you tin can but click it and then you see that information technology's our div and in that location are a number of attributes here that we have available to us such as class list so I can type dot course list and that is going to give united states of america a dom token list and so it's showing united states of america that correct at present the nonActiveHeading is within of the class listing.

large

And every bit you may also notice it gets returned in an array really. And then if I articulate this out what I could do is I can actually check to run across if the class I'one thousand looking for is included inside of those classes that are there. And then I tin can say in this conditional if heading.classList and I'm going to utilize just some pure Javascript code here and say contains and from there I tin can pass in activeHeading. And so what this is going to do is it's going to go through that array that gets returned and it'due south going to get through that array classes and it's going to say is there a word in at that place? Is at that place a string in there called activeHeading?

Considering if there is I want to perform ane process and if there's not I want to perform a dissimilar procedure so I'm going to say if the heading contains active heading and so from there. So what I desire to do is I desire to add then remove a class and let'southward come up upwards to our div and accept information technology dorsum to our showtime state which is going to be where it actually starts with active heading then from here. At that place are going to exist two processes that we want to take place and then I'm gonna say heading.classList.remove. So all we're doing is we're working with an array right here so we can remove items and add items to that array.

So hither I'k going to say remove the activeHeading and then I'yard going to add the nonActiveHeading and so I'g gonna say add nonActiveHeading. And so that is what we want to happen. And then if we come here you striking refresh. So right at present we have our agile heading and if we click "Hi in that location" now it's working and so this is working perfectly. If y'all notice all I did was check to encounter if the activeHeading was there if so it removes that course proper name and then adds this ane and you tin exam this out.

Permit's hit refresh become it back to where it was and hit inspect and here you lot tin can see that activeHeading is the current class.

large

Now watch what happens when I click on it when I click on it. It removes that class name and information technology replaces it with nonActiveHeading

large

large

then that is exactly what we're looking for. Only now if I click on it over again naught happens and the reason for that is because our conditional is only checking for activeHeading. We don't have any else statement then let's add that now. And then you say else and the process is going to exist exactly similar what we had hither except at present it's just going to be reversed. Then permit'south get rid of this and say nonActiveHeading. And we desire to, in this case, add activeHeading and then hitting save and now allow's hit refresh once again and now it should exist toggling so now when I click information technology, it should add together the form of nonActive remove active and then vice versa. So I click it that works click it again that worked again and you tin can click this a meg times it's going to be doing the exact same thing and then that is working perfectly.

And so yous saw how we were able to work with a course listing exactly similar how we'd piece of work with an array. Now that is 1 way of doing it earlier I end this guide I want to show y'all i other way that might be a little bit easier. And this is something that you can do in this onclick case say that y'all have a large number of classes then say instead of just activeHeading yous may accept something that is also y'all know myCustomHeading and a bunch of other elements and yous don't desire to mess with those. And that's perfectly fine in that case what we did here will piece of work.

But if yous do accept some type of component on the page and y'all do not care about overriding them what you can do if you lot do not care nearly overwriting is y'all can get rid of all of this and then say Heading.className and and so this is going to be a nonActiveHeading copy this down and here it's going to be activeHeading.

heading.onclick = () => {            if            (heading.classList.contains(              '              activeHeading              '            )) {     heading.className =                          '              nonActiveHeading              '            ;   }            else            {     heading.className =                          '              activeHeading              '            ;   } }          

Then if I hit save now if we come back hit refresh I click it and there information technology's working. And then detect how the behavior is completely identical. Where the difference says is if you had other elements and then if I come up support here and say another form name to offset off by save here and striking refresh. Yous can encounter that I take activeHeading and someOtherClassName set and that'southward perfectly fine.

large

There are many times where yous need to accept multiple classes inside of one component but if I click this discover how it'due south gone. It only sets nonActiveHeading in that location.

large

If I click it again information technology no longer has that custom one so that is a scenario where that would be a bad idea.

large

Now if I annotate this out and come up back here and select all of this I'm going to put it back where we had earlier. Hit salve and now if I come up back and hit refresh if I click on it you lot can come across that it didn't get rid of someOtherClassName.

large

All it did was information technology looked at the stack of classes and so it looked at information technology like an array because that's how it'southward treating it here information technology's just treating it like a traditional array and all it'southward doing is saying OK I want yous to remove that activeHeading and then I want y'all to add together nonActive and completely ignore this other value.

Click it again and we all the same have our other custom class name at that place and so that's a reason why I wanted to show you both options. If you have a state of affairs where yous do not have whatsoever other course names y'all don't care nearly overwriting them. This is probably a little bit easier to read and so this is something that I would go with if I had a unmarried course name I just set the entire course proper name equal to the value I desire.

            heading.onclick = () => {            if            (heading.classList.contains(              '              activeHeading              '            )) {       heading.className =                          '              nonActiveHeading              '            ;     }            else            {       heading.className =                          '              activeHeading              '            ;     };   }          

Simply if you do have other elements to keep in mind and that you don't want to override then this is how you can exercise that.

            heading.onclick = () => {            if            (heading.classList.contains(              '              activeHeading              '            )) {       heading.classList.remove(              '              activeHeading              '            );       heading.classList.add(              '              nonActiveHeading              '            );     }            else            {       heading.classList.add(              '              activeHeading              '            );       heading.classList.remove(              '              nonActiveHeading              '            );     };   }          

Then in review what nosotros've done in this guide is pretty impressive what y'all at present know how to do. This is a very significant portion of what you need to know in order to piece of work with JavaScript in the browser and that is that we created a full HTML document. From there we were able to select items using getElementbyId we're able to select the heading item there. Then we created a click listener where we were able to toggle different classes on the folio merely based on the user behavior.

And then very nice work if you went through all of that.

Code

<!DOCTYPE html> <html lang='en'> <caput>   <meta charset='UTF-8'>   <title></title> </head>  <style>   .activeHeading {     colour: firebrick;     font-size: 2em;     cursor: pointer;   }   .nonActiveHeading {     color: cornflowerblue;     font-size: 4em;     cursor: pointer;   } </style> <body>    <div id="mainHeading" form="activeHeading">     Hi there   </div>  </trunk>  <script>   const heading = certificate.getElementById('mainHeading');   heading.onclick = () => {     if (heading.classList.contains('activeHeading')) {       heading.classList.remove('activeHeading');       heading.classList.add('nonActiveHeading');     } else {       heading.classList.add('activeHeading');       heading.classList.remove('nonActiveHeading');     };   }     heading.onclick = () => {     if (heading.classList.contains('activeHeading')) {       heading.className = 'nonActiveHeading';     } else {       heading.className = 'activeHeading';     };   } </script> </html>          

suttondefecdoing.blogspot.com

Source: https://devcamp.com/trails/javascript-in-the-browser/campsites/javascript-dom/guides/how-to-add-and-remove-classes-vanilla-javascript

Post a Comment for "Click on Something to Add Class Then Click Again to Remove Vanilla Javascript"