I using same onclick
function on two span
, When clicking on text 1 span
it is adding active
class and when clicking again removing the class. It is working fine on both span’s.
I just want if when clicked text 1 span
so the active
class is added to text 1 span
and when i click on text 2 span
add active
class to this span but remove it from text 1 span
.
Available on codepen https://codepen.io/hnpiocyj-the-encoder/pen/VwRZBrW
<span class="selected" onclick="select(this);">text 1</span>
<span class="selected" onclick="select(this);">text 2</span>
function select(i){
e = window.event
$(i).toggleClass("active");
e.stopPropagation();
}
I want if text 1 span has active class and when i click on text 2 span add active class but also i want to remove the active class from text 1 span.
6
Answers
To do what you require you simply need to remove the class from all other
.selected
elements, except the one which you clicked on.Also note that there’s a couple of other changes your should make to improve the quality of your code. Firstly, don’t use inline
onclick
attributes. They’re bad practice and have been superceded by unobtrusive event handlers which can be bound in the JS itself.Seconly, don’t use the global
window.event
object as it’s not available in all browsers. If you use unobtrusive handlers, then your handler function will be provided the Event as an argument which you can use to identify the element that fired the event.With those changes made, your code would look something like this:
You just need to get all the
active
spans in your function and remove theactive
class from them. After removing, you can make use of yourthis
object, passed in the function argument, to add a newactive
class.See the demo below:
If you are using jQuery, you can use it’s function
is()
to check if the target element is equal to another element:To achieve the behaviour you’re looking for, where clicking on one span adds the ‘active’ class to it and removes the ‘active’ class from the other, you’ll need to modify your select function. Currently, your function toggles the ‘active’ class for the clicked element but doesn’t affect the other element. Here’s an updated version of the function that should work for your requirements:
Also…
You can simply use the below jQuery code to achieve this.