I am totally new to web programming. I built a slide navigation and wanted to make it slide from the left to the middle. The thing is I just found a Jquery code. I tried to look it up by searching on google but the matches didn't match to the thing I was looking for.
Here is the Code:
$('.nav-side .nav-toggle').on('click', function(e){
e.preventDefault();
$(this).parent().toggleClass('nav-open');
})
I would like to know if I can translate this into Javascript because I would like to continue using HTML, CSS and Javascript.
Could someone help me out?
In pure JavaScript it should be something like this:
var elements = document.querySelectorAll('.nav-side .nav-toggle');
[].slice.call(elements).forEach(function(element) {
element.addEventListener('click', function() {
element.parentNode.classList.toggle('nav-open');
return false;
}, false);
});
JSFiddle: https://jsfiddle.net/r0x7zehz/
You can use classList.toggle()
:
document.getElementsByClassName('nav-toggle')[0].addEventListener('click', function(e){
e.preventDefault();
e.target.parentNode.classList.toggle('nav-open');
});
Here is a codepen example.
This is pure javascript code
function clickHandler(dom)
{
dom.addEventListener('click', function(e) {
dom.parentNode.classList.toggle('nav-open');
return false;
}, false);
}
document.querySelector('.nav-side .nav-toggle').map(clickHandler);
Here is your HTML
<a href="#" class="nav-toggle" onclick="toggleFunction(this)">Toggle</a>
And Here is your javascript which adds style="display:none;" when the parent style="display:block;". vice versa
<script>
function toggleFunction(elem){
var parent = elem.parentNode;
if(hasClass(parent, 'nav-open')){
parent.classList.remove('nav-open');
}else{
parent.className += " nav-open";
}
}
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
</script>
I just got it by writing:
function clickHandler(dom){
dom.parentNode.classList.toggle('nav-open');
return false;
}
But thanks everyone for the answers :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.