Easy way to set active class with javascript - javascript

I tried to find the easiest way to set the active class to the active Navbar point.
My Code looks like this:
function setActive(i) {
$(document).ready.getElementById(i).addClass("active");
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="../js/main.js"></script>
<script>
setActive("contact");
</script>
</head>
<body>
<a id="contact" class="nav-link" href="">Example</a>
</body>
Why is this not working?
Thanks for the help!

In jQuery, you use $().addClass(). You should call the function inside $(document).ready(), not have the function run only if the document has loaded.
In your setActive function, it looks like you are mixing up Javascript and jQuery. You should only use one or the other.
$(document).ready.getElementById(i).addClass("active");//this line is a syntax error
.active{
color: green;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function setActive(i) {
$('#'+i).addClass("active");
}
$(document).ready(function(){
setActive("contact");
});
</script>
</head>
<body>
<a id="contact" class="nav-link" href="">Example</a>
</body>
With pure Javascript, you can use Element.classList.add() to add a class to an element.
.active{
color: green;
}
<head>
<script>
function setActive(i) {
document.getElementById(i).classList.add("active");
}
document.addEventListener("DOMContentLoaded", function(){
setActive("contact");
});
</script>
</head>
<body>
<a id="contact" class="nav-link" href="">Example</a>
</body>

To set the contact active you need to this it this way. You already have jQuery in you code so it is more easy.
function setActive(tag){
//This bloc is optinal. It will remove active class from all other elements. You may not need that
$('body a').removeClass('active');
//End optional block
$(`#${tag}`).addClass('active');
}
$(document).ready(function(){
setActive('contact')
});

please try:
function addActive(el){
document.querySelector(el).classList.add("active");
}

You should call setActive("content") inside main.js inside a ready function
You are also missing the id selector (#) in your jQuery selector
$( document ).ready(function() {
setActive("contact");
});
function setActive(id){
$(`#${id}`).addClass("active");
}
.active{
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="contact" class="nav-link" href="">Example</a>

Try this
function setActive(i) {
document.getElementById(i).classList.add("active");
}
function setDisable(i) {
document.getElementById(i).classList.remove("active");
}
.active{
background-color: yellow;
color: red;
}
<html>
<body>
<button type="button" onclick="setActive('demo')">
Activate
</button>
<button type="button" onclick="setDisable('demo')">
Disable
</button>
<p id="demo">Here</p>
</body>
</html>

Related

How to use event.target.matches to match div element

<!DOCTYPE html>
<html>
<head>
<style>
.dropdown-content a{
display: block;
background-color: blue;
}
</style>
</head>
<body>
<div class="dropdown-content">
<a>1</a>
<a>2</a>
</div>
<script>
window.onclick = function(event){
if(!event.target.matches('.dropdown-content')){
alert("foo");
}
};
</script>
</body>
</html>
I'm trying to make alert(foo); execute only when we are NOT clicking on anything inside of the div tag in the body. Unfortunately, it executes no matter where I click. Why?
window.onclick = function(event){
if (document.getElementsByClassName('dropdown-content')[0].contains(event.target)){
// inside
} else{
// outside
alert('foo');
}
};
.dropdown-content a{
display: block;
background-color: blue;
}
<div class="dropdown-content">
<a>1</a>
<a>2</a>
</div>
Get your element and use contains to check whether click is in or outside. If outside then alert.
matches is not working because you are clicking in a tag which is not having .dropdown-content tag. So everytime value comes false. And it alert('foo')
As i seen you have to add content to de div.conta, i made a demo
And work with the dom, className( imade right, but can use any):
<div class="dropdown-content">
abc
<a class="name">1</a>
<a>2</a>
</div>
window.onclick = function(event){
console.log(event.target.className);
if(event.target.className!=='dropdown-content'){
console.log("foo");
}
};
If you're using jQuery you can do the following:
$(event.target).closest('.dropdown-content').length
See the following JSFiddle:
https://jsfiddle.net/4nb691a0/
Because your if statement returns false and with ! operator returns true. It happens because when you clicked inside the div your actual target is <a> element which does not have class .dropdown-content.
When click outside the div it also does not have class .dropdown-content. So your statement always returns false but with ! operator it becomes true.
Try this:
<!DOCTYPE html>
<html>
<head>
<style>
.dropdown-content a{
display: block;
background-color: blue;
}
</style>
</head>
<body>
<div class="dropdown-content">
<a class="link">1</a>
<a class="link">2</a>
</div>
<script>
window.onclick = function(event){
if(!event.target.matches('.link')){
alert("foo");
}
};
</script>
</body>
</html>

JavaScript Uncaught SyntaxError: missing )

I have one link
<a ng-click="logout()">
I want to change the above link to below code
<a ng-click="logout()" onclick="setTimeout(function () { window.location = 'https://demo.test.ca/log'; }, 3000);">
I am using third party solution, In this you can change the code directly without modifying the actual code.
But the problem is that when I write policy for changing the code. When this application is loaded it gives me the following error
Uncaught SyntaxError: missing ) after argument list
So please help me to fix this.
you have to close <a> tag
<a ng-click="logout()" onclick="setTimeout(function () { window.location = 'https://demo.test.ca/log'; }, 3000);">
</a>
a:link {
text-decoration: none;
}
a:visited {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a:active {
text-decoration: underline;
}
<!DOCTYPE html>
<html>
<body>
<a ng-click="logout()" type="button" value="Load new document" onclick="myFunction()">Click Me</a>
<script>
function myFunction() {
setTimeout(function () {
window.location.assign("https://stackoverflow.com/")
}, 3000);
}
</script>
</body>
</html>
This should work,
Can you try
<!DOCTYPE html>
<html>
<body>
<a ng-click="logout()" type="button" value="Load new document" onclick="myFunction()">Click Me</a>
<script>
function myFunction() {
setTimeout(function () {
window.location.assign("https://stackoverflow.com/")
}, 3000);
}
</script>
</body>
</html>
If you are using angularjs and ng-click then do it properly and remove that onclick and assign function to $scope in your controller/directive/component so your template would look like:
<a ng-click="logout()">Logout</a>
and in your controller/directive/component in logout function:
$scope.logout = function () {
// logout code ....
$timeout(()=> {$window.location = 'https://demo.test.ca/log'; }, 3000);
}
Also make sure you inject $window and $timeout, if you don't already have it you will need to add it.

Failure to edit div on nav click event

So I typed up most of the pertinent information into the code itself
I would love a explanation of whats happening and why, especially between the multiple outcomes of .text .html and not returning what i want
<DOCTYPE! Html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style>
p{color: white;
background: black;}
</style>
<script>
$('document').ready(function() {
$(document).on('click', '.nav', function() {
document.getElementById('text').innerHTML=$(this).html;
});
});
</script>
</head>
<body>
This is a test html to trouble shoot the functionality of the script, the above script runs and does what it needs to in other aspects but when trying to add in the ability to edit a divs text based on the nav clicked on theres a error.
when using ".text" in the script i get <p> function (a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)} </p> in my div,when i use ".html" in my script i get <p> function (a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)} </p>
<ul id="nav">
<li class="nav"> This is the text that should be placed in the div </li>
</ul>
<div id="text"> this text should be changed </div>
</body>
</html>
The jQuery method .html() is a function you need to call it / use (). Or go vanilla and just do this.innerHTML.
That means:
$(document).on('click', '.nav', function() {
document.getElementById('text').innerHTML = this.innerHTML;
});
Example in the snippet:
$('document').ready(function() {
$(document).on('click', '.nav', function() {
document.getElementById('text').innerHTML=this.innerHTML;
});
});
p{color: white;
background: black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is a test html to trouble shoot the functionality of the script, the above script runs and does what it needs to in other aspects but when trying to add in the ability to edit a divs text based on the nav clicked on theres a error.
when using ".text" in the script i get <p> function (a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)} </p> in my div,when i use ".html" in my script i get <p> function (a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)} </p>
<ul id="nav">
<li class="nav"> This is the text that should be placed in the div </li>
</ul>
<div id="text"> this text should be changed </div>
Something like this:
$(document).ready(function () {
$(".nav").on('click', function() {
$("#text").html( $(this).html() ); // Getting too nested here
}
}

addEventListener not working in javascript

I am learning addEventListener,I was testing one of the example but its not working .Can anybody tell me what i am doing wrong
<html>
<head>
<script type="text/javascript">
function click_handler1() { alert("click_handler1"); }
function click_handler2() { alert("click_handler2"); }
document.getElementById("id1").addEventListener("click", click_handler1, false);
document.getElementById("id2").addEventListener("click", click_handler2, false);
//window.addEventListener("load", setup, false);
</script>
</head>
<body>
<a id="id1">some stuff</a>
<a id="id2">stuff</a>
</body>
</html>
Thanks
Your elements are not found because you're executing the javascript before you've added the elements.
Try moving the script to the bottom of the body:
<html>
<head>
</head>
<body>
<a id="id1">some stuff</a>
<a id="id2">stuff</a>
<script type="text/javascript">
function click_handler1() { alert("click_handler1"); }
function click_handler2() { alert("click_handler2"); }
document.getElementById("id1").addEventListener("click", click_handler1, false);
document.getElementById("id2").addEventListener("click", click_handler2, false);
//window.addEventListener("load", setup, false);
</script>
</body>
</html>
Move this to the end of the document, or wrap it with an onload function:
window.addEventListener('load',function(){
document.getElementById("id1").addEventListener("click", click_handler1, false);
document.getElementById("id2").addEventListener("click", click_handler2, false);
});
Your code doesn't work because the DOM is not ready yet and you are already trying to fetch id1 and id2.
Your code throws below error in console:
Uncaught TypeError: Cannot call method 'addEventListener' of null
which specifies you need to first define your html element (anchor in this case) and then call methods on it.
What you are doing is - first calling method (addEventListener in this case) and defining the html element (anchor in this case) later on.
<html>
<head></head>
<body>
<a id="id1">some crap</a><br>
<a id="id2">crap</a>
<script type="text/javascript">
function click_handler1() { alert("click_handler1"); }
function click_handler2() { alert("click_handler2"); }
document.getElementById("id1").addEventListener("click", click_handler1);
document.getElementById("id2").addEventListener("click", click_handler2);
</script>
</body>
</html>

Passing a div class into a javascript function

Is it possible to pass the class of a div into a javascript function? I am using square space so I cannot add an id to the div, but I can get it to work with div's that do have id's. Also, I already have loaded the jquery.
This is what I am thinking so far, thanks in advance!
<script type="text/javascript">
function unhideme(arg) {
$(arg).slideDown()
}
function clickme(arg1, arg2) {
unhideme(arg1);
unhideme(arg2);
//other stuff
}
</script>
<style type="text/css">
#myid{
display:none
}
.klass{
display:none
}
</style>
<form><input type="submit" onclick="clickme('#myid','.klass')">
<div id="myid"></div>
<div class="klass"></div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function unhideme(classname) {
$(classname).slideDown();
}
function clickme(classname) {
unhideme(classname);
}
</script>
<style>
.klass {
display: none;
}
</style>
<form>
<input type="submit" onclick="clickme('.klass');return false;">
<div class="klass">testdown</div>
</form>

Categories

Resources