newbie newbie -4 years ago 111
jQuery Question

jQuery - using addClass on specific window width with toggleClass on same element

i have a on resize add class jQuery function which help me show an element on a certain window size:

<div class="v-menu"></div>
<div id="menu">
<a href="#">a</a>
<a href="#">b</a>
<a href="#">c</a>
</div>


 

(function($) {
var $window = $(window),
$html = $('#menu');
function resize() {
if ($window.width() < 612) {
return $html.addClass('close');
}
else{
$html.removeClass('close');
$html.removeClass('open');
$('*[class=""]').removeAttr('class');
}
}
$window
.resize(resize)
.trigger('resize');
})(jQuery);


and i can toggle it with another function:

$(".v-menu").click(function(){
$("#menu").toggleClass("open");
$("#menu").toggleClass("close");
});


the problem is if i toggle the element to open and then resize the window jQuery keep adding the
close
class to the element:

<div id="menu" class="open close">
<a href="#">a</a>
<a href="#">b</a>
<a href="#">c</a>
</div>


how can i solve that?

Answer Source

Based on your comment

i dont want that close class add when the open class added.

https://api.jquery.com/hasclass/

 if ($window.width() < 612){
         if(!$html.hasClass('open')) {
                  return $html.addClass('close');
         }
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download