How to remove the class of an element in javascript? - javascript

I am trying to open a submenu, and that when selecting one of its options the submenu closes, for this I add and remove the class show as seen in the following code
$open.addEventListener("click", (e) => {
e.preventDefault();
$submenu.classList.add("show");
document.documentElement.addEventListener("click", () => {
$submenu.classList.remove("show");
});
$containertopics= document.getElementById("container_topics");
$listtopics= document.getElementsByClassName("list__topics");
loadsubmenu();
for (let i of $listtopics) {
i.addEventListener("click", (e) => {
$submenu.classList.remove("show");
});
}
});
but the problem is that clicking on an item in the submenu does not remove the class, I have already tried to remove all its classes and add them one by one except the class see, but it doesn't work for me.

This code works:
$open.addEventListener("click", (e) => {
e.preventDefault();
loadsubmenu()
$submenu.classList.toggle("show");
});
for (let i of $listtopics) {
i.addEventListener("click", (e) => {
$submenu.classList.remove("show");
});
}
window.addEventListener('click', (e) => {
if (e.target == $submenu) {
$submenu.classList.remove("show");
}
})
There was some problem with eventListeners as you are assigning a function every time '$open' is clicked.

You haven't shared your HTML code here to know to us what is the error generate from your code. So I have created a example for you. Get the Idea. You can use .removeClass method.
$(document).ready(function(){
$("button").click(function(){
$("p").removeClass("highlight");
});
});
.highlight{
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="highlight">Remove class from the element</p>
<button type="button">Remove Class</button>
here is the JSfiddle

Related

Using JS How to call click function once only which will be equivalent to .one jQuery

Hello could someone help me? I'm having trouble transforming this part of my code to JS:
$(".custom-select-trigger").on("click", function() {
$('html').one('click',function() {
$(".custom-select").removeClass("opened");
});
$(this).parents(".custom-select").toggleClass("opened");
event.stopPropagation();
});
I have it so far:
const customSelectTrigger = document.querySelector(".custom-select-trigger");
const customSelect = document.querySelector(".custom-select");
function showOptions(e) {
e.preventDefault();
customSelect.classList.toggle("opened");
e.stopPropagation();
}
but I'm not able to do this part for javascript:
$('html').one('click',function() {
$(".custom-select").removeClass("opened");
});
Here is working code for to remove class opened from your custom select when you press anywhere in the DOM.
You need to use JS addEventListener and click function to do this.
To remove class from an element we can use .remove function and getting the classList of your element by querySelector which will .custom-select
Edit: If you just want to use the click function once only per DOM load. Then setting setting the args { once: true } will only invoke the function once.
I have recreated your example and its working.
Run snippet below.
//Getting HTML element
const htmlElement = document.querySelector("html");
//Getting element where to remove the class from
const customSelect = document.querySelector(".custom-select");
//Adding eventlistener to remove class opened from classList
htmlElement.addEventListener("click", function(e) {
customSelect.classList.remove("opened");
console.log('Class Removed')
e.preventDefault();
},{ once: true });
.opened {
background-color: red;
}
<html>
<h3>
Click anywhere on the DOM to remove class from Custom select
</h3>
<div class="custom-select opened">
My Custom Select
</div>
</html>

JQuery click-function for each link does not work

I am currently working on a "collapse all"-button for Bootstrap 3 collapsible plugin. It seems to work fine, but only if I have got only one single collapsible on my page. When I add another one, my method will still just work in the first link item.
Here ist my JS:
$(function () {
$("#toggle-all").click(function (e) {
e.preventDefault();
var $hidden = $(this).parent().data("hidden");
if ($hidden == "false") {
$(this).parent().find(".collapse.in").each(function () {
$(this).collapse("hide");
});
$(this).parent().data("hidden", "true");
} else {
$(this).parent().find(".collapse").not(".in").each(function () {
$(this).collapse("show");
});
$(this).parent().data("hidden", "false");
}
$(this).find("i").toggleClass("fa-plus fa-minus");
});
});
And here a fiddle to try: http://jsfiddle.net/rMdLZ/
Any ideas why it does not work as expected?
Thanks,
Julian
You are using 2 id's. Id's must be unique elements on each document.
See this SE question for reference: Two HTML elements with same id attribute: How bad is it really?
Change it to Classes:
$(function () {
$(".toggle-all").click(function (e) {
e.preventDefault();
var $hidden = $(this).parent().data("hidden");
if ($hidden == "false") {
$(this).parent().find(".collapse.in").each(function () {
$(this).collapse("hide");
});
$(this).parent().data("hidden", "true");
} else {
$(this).parent().find(".collapse").not(".in").each(function () {
$(this).collapse("show");
});
$(this).parent().data("hidden", "false");
}
$(this).find("i").toggleClass("fa-plus fa-minus");
});
});
http://jsfiddle.net/vP4e9/1/
Don't use ids. Use classes and I think you should do fine.
Why?
Because the ids have to be unique through out the frame.
$('#someId') will always return you the same element, but $('.someClass') will return you all elements with someClass class
I've changed $("#toggle-all").click to $(".toggle-all").click and added the toggle-all class the the collapse all buttons. And it works fine.
Demo

Select all elements except a certain class

I'm trying to hide .menu_branch using jQuery slideUp() only if the user clicks off of .menu_root. I'm not getting any errors but the click() function is executing even if .menu_root is clicked. Any ideas? jQuery or straight JavaScript are both fine by me. Thanks!
HTML:
<span class="menu_root">Menu</span>
<ul class="menu_branch">
<li>Home</li>
<li>FAQ</li>
<li>About</li>
<li>Contact</li>
</ul>
CSS:
.menu_branch {
display:block;
}
Jquery:
$("body:not(.menu_root)").click(function(){
$(".menu_branch").slideUp("fast");
});
I've also tried:
$("body").not(".menu_root").click(function(){
$(".menu_branch").slideUp("fast");
});
As well as replacing body with * in both instances, all with the same result.
One possible solution is to prevent the propagation of click event from menu_root
$(document).click(function () {
$(".menu_branch").slideUp("fast");
});
$('.menu_root').click(function (e) {
e.stopPropagation();
})
Demo: Fiddle
Your code will ignore a body element with class menu_root like <body class="menu_root">
You can try this:
$("body").click(function(event){
if ( $(event.target).hasClass("menu_root") ) {
return false;
}
$(".menu_branch").slideUp("fast");
});
http://jsfiddle.net/WzW2D/2/
Late to the party again but this should work for you. Clicking .menu_root will toggle the menu. Clicking anywhere else will close it (if its open).
$(document).on("click", function(e) {//When the user click on any element:
if($(".menu_branch").is(":visible")){//If the menu is open...
$(".menu_branch").slideUp("fast");//close it.
} else if ($(e.target).hasClass("menu_root")){//Otherwise, if the user clicked menu_root...
$(".menu_branch").slideDown("fast");//open it.
}
});
http://jsfiddle.net/xGfTq/
try
$(document).click(function () {
$(".menu_branch").slideUp("fast");
});
$('.menu_root').click(function () {
return false;
})

jQuery - who really clicked me?

I have this jsbin ( prev answers didn't help much)
 
<span id="mySpan" > click here </span>
  <br/> 
  <input id="myCb" type="checkbox"/>
i have a listener for checkbox click which do Alert...
However , clicking on the span is triggering the click event for the checkbox.
I want to detect - who really made the checkBox execute the alert.
But !
I want :
if first clicked the span , alert
i was originally pressed by mySpan
else
if first clicked the checkbox , alert i was originally pressed by myCb
$("#mySpan").on('click',function (e)
{
$("#myCb").trigger('click');
});
$("#myCb").on('click',function (e)
{
doWork(e)
});
function doWork(e)
{
alert('i was originally pressed by '+$(e.delegateTarget).attr('id') );
}
p.s. i can use a global field or flag solution - which i DONT WANT.
i will be glad to have a "moving the data" through the e param - solution.
thanks.:)
edit
jQuery does support moving data , but i cant write the right code
This works for me,
<html>
<head>
<style>
</style>
<script src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$("#mySpan").on('click',function (e){
$("#myCb").trigger('click','span');
});
$("#myCb").on('click',function (e,span){
var ele = span || 'cb';
doWork(ele);
});
function doWork(ele){
alert('i was originally pressed by ' + ele );
}
})
</script>
</head>
<body>
<span id="mySpan" style="width:100px;height:100px;" > click here </span>
<br/><br/><br/>
<input id="myCb" type="checkbox"/>
</body>
</html>
Fiddle
how about this.
$("#mySpan").on('click',function (e)
{
$("#myCb").trigger(e);
});
$("#myCb").on('click',function (e)
{
doWork(e);
});
function doWork(e)
{
alert('i was originally pressed by '+$(e.target).attr('id') );
}
It worked for me and it was the closest to your original code.
in action http://jsbin.com/ixanup/2/edit#javascript,html
$("#mySpan, #myCb").on('click', function (e) {
alert('I was originally pressed by ' + e.target.id);
console.log($(e.target)); /* jQuery reference to the clicked element */
if (e.target.id === 'myCb') {
/* do code only if checkbox was clicked */
}
});
Example fiddle: http://jsfiddle.net/4AVZz/
maybe this code helpful for you:
$("#mySpan").on('click',function (e)
{
alert('i was originally pressed by '+$(e.delegateTarget).attr('id') );
if($("#myCb").attr('checked')=="checked")
$("#myCb").removeAttr('checked');
else
$("#myCb").attr('checked','checked');
});
$("#myCb").on('click',function (e)
{
alert('i was originally pressed by '+$(e.delegateTarget).attr('id') );
});
$("#mySpan").on('click',function () {
var cb = $("#myCb");
if(cb.is(':checked')) {
cb.removeAttr('checked');
} else {
cb.attr('checked', true);
}
doWork.apply($(this));
});
$("#myCb").on('click',function (e) {
doWork.apply($(this));
});
function doWork(e) {
console.log('i was originally pressed by '+$(this).attr('id') );
alert('i was originally pressed by '+$(this).attr('id') );
}
I've modified your example as per your requirement. And saved as a new version.
Please have a look at this. http://jsbin.com/axaqer/7/edit
I would do something like this:
$(function() {
$('.row span, .row input[type="checkbox"]')
.on('click', function (evt) {
triggerCheckbox($(this), evt.currentTarget.tagName);
doWork(evt.currentTarget.tagName);
});
});
function doWork(elm) {
// elm with either be INPUT or SPAN
console.log('I was originally pressed by ' + elm);
}
function triggerCheckbox(elm, evt) {
// if it's a SPAN, let's change the checkbox value without
// triggering the click event
if(evt.currentTarget.tagName === 'SPAN') {
var ckb = $(elm).closest('.row').find('input[type="checkbox"]');
$(ckb).prop('checked', !$(ckb).prop('checked'));
}
}
and it will not matter what ID you have, it will work with all, as long as you have a wrapper grouping the both.
in HTML, I added a <div> to wrap your content, so it will look like:
<div class="row">
<span id="mySpan">click here</span>
<br/><br/><br/>
<input id="myCb" type="checkbox"/>
</div>
live example can be found on JsBin as well.
why dont you use,
e.currentTarget
?

Get id of clicked element without putting any js code in the html

I need to get the ID of an element that was clicked, but I need to to keep all my js and html separate. normally id just use 'this.id' in the html. Any other ways?
This is what e.target is for. You can add an event listener anywhere you want, as long as the click event is allowed to bubble up to it (which happens by default) you can catch it. A basic example:
document.addEventListener('click', function(e) {
alert(e.target.id);
});
Clicking on each will alert its id. Hope this helps :)
<button id="foo">foo</button>
<button id="bar">bar</button>
<button id="baz">baz</button>
EDIT
http://jsfiddle.net/95NZ8/
Try something like this:
$(document).ready(function () {
$("#someWrapper").each(function () {
$(this).on('click', function () {
alert(this.id);
});
});
});
window.onclick = e => {
console.log(e.target.id);
}
to get element, tagname, classname , other attributes
window.onclick = e => {
console.log(e.target);
console.log(e.target.tagName);
console.log(e.target.className);
console.log(e.target.id);
}

Categories

Resources