Target the css class with some JS - javascript

Hello I currently have this inline JS on my wordpress navigation menu
login
I was told it is better to use a regular menu item then just give it a class then target the class with some JS. I tried searching for examples but can't find that works for me. Could someone share a sample code to point me in the right direction?
thanks

I think this is what you are told.
var link = document.querySelector(".js-link");
link.addEventListener("click", (e) => {
e.preventDefault();
//do whatever you want hear
console.log("redirect to another page");
});
Google
The way you do will make your code messy, hard to read and maintain. So we should separate html, css and js code. And to make your javascript and style not affect each other when you change your code, you should naming the class which you want to use javascript different with class you want to style.
For example I using class "js-link" just for javascript, not to style it. If I want to style the link I will add another class for it.

Related

How do I apply a class to all links on a specific page using JavaScript?

I have a page on WordPress with hundreds of links and I'd like to style them all with a CSS class without having to add the class to each link, line by line, and want to use JavaScript to do it.
How can I achieve this?
I want only https://staging.startupdevkit.com/resource-library-version-1/ to be affected using my CSS class, "link-style"
I found a response on another similar thread with this:
document.querySelectorAll('a[href="'+document.URL+'"]').forE‌​ach(function(elem){e‌​lem.className += ' current-link')});
I tried it, probably incorrectly, with this:
document.querySelectorAll('a[href="'*https://staging.startupdevkit.com/resource-library-version-1/*'"]').forE‌ach(function(elem){e‌lem.className += 'link-style')});
Am I doing it wrong or am I not using the correct solution, or both?
Thank you for your help in advance!
const URL = "https://staging.startupdevkit.com/resource-library-version-1/";
document
.querySelectorAll(`a[href="${URL}"]`)
.forEach(element => element.classList.add('link-style'));
try this
[...document.querySelectorAll('a[href^="https://staging.startupdevkit.com/resource-library-version-1/"]')].forE‌ach(function(elem){e‌lem.classList.add('link-style')});
it checks all href starting from
https://staging.startupdevkit.com/resource-library-version-1/

Auto Swap External CSS Stylesheet with toggle scripting

Hi I am trying to get this script to toggle back to original CSS external stylesheet.
I have the following code that works.
$(document).ready(function() {
$("#css-master2").click(function() {
$("link[title=change]").attr({href : "css/master2.css"});
});
});
Whenever someone clicks on anything with id #css-master2 it changes the external style sheet to master2.css (that part works fine).
What I would like it do is change back to the original master1.css if they click on it again. Something like toggle?
Any help would be greatly appreciated.
Check for the link tag's href, if it equals master2, switch back to master1 like the same way above.
Can't think about why you'd do this, considering the exact thing can be done using css classes instead of two different files.

JQuery Toggle Divs Based On Index not retoggle when clicked twice

and thank you for reading this question. Let me preface this by saying that I am not a programmer and only have tried to learn javascript to make my own websites look and function the way I want.
I have a page with several hidden divs. I'm using elements with the same class and different targets to trigger this Jquery
jQuery(function () {
jQuery('.nav').click(function () {
var index = $(this).index(),
newTarget = jQuery('.targetDiv').eq(index);
jQuery('.targetDiv').not(newTarget).slideUp('fast')
newTarget.delay('fast').slideToggle('fast')
return false;
})
});
So my ".targetDiv"s look like this:
<div class=".targetDiv" style="display:none">div1</div>
<div class=".targetDiv" style="display:none">div2</div>
<div class=".targetDiv" style="display:none">div3</div>
And the "navigation" would look something like this
link1
link2
link3
This is not my code, and I got it from here: http://forum.jquery.com/topic/slidetoggle-multiple-divs-31-5-2013
It works exactly as it is supposed to and I have no complaints about that. When you click on a link, the corresponding div toggles, but when you click the same div again right afterwards, it toggles again and slides up (which is how the code is written). I want to stop that from happening, and since I am new to Javascript and Jquery I can't figure out how to do it. My non programmer mind assumes that there should be some kind of if else clause, where you would say:
if .targetDiv is :visible, then do not toggle newTarget. However when I tried to do that, it did not work.
if($(".targetDiv").is(":hidden")) { jQuery(function () {
jQuery('.nav').click(function () {
var index = $(this).index(),
newTarget = jQuery('.targetDiv').eq(index);
jQuery('.targetDiv').not(newTarget).slideUp('fast')
newTarget.delay('fast').slideToggle('fast')
return false;
})
});}
else {alert("already open")}
I don't know how else I should handle this, but it must be possible and I am probably just thinking of how to achieve what I want in entirely the wrong way. I understand very little about javascript, but I am not asking for someone to write this for me, I'd rather have someone tell me what it is that I am doing that is incorrect, then explain what it is I should be trying to do. Then I can use google to search for the way to achieve that.
Again, thank you for taking the time to read this and hopefully I've been detailed enough for some answers.
You just need to wrap the two 'slide' lines in the if statement, like so:
if (!newTarget.is(':visible'))
{
jQuery('.targetDiv').not(newTarget).slideUp('fast');
newTarget.delay('fast').slideToggle('fast');
}
You may also want to fix a few issues with the html, e.g. take the periods out of your class names. When querying for DOM elements, the "." means, "Find the things that have a class called _[whatever follows the dot]". Don't put dots in the classes themselves.
You may also want to take out the href attributes of the <a> tags. They aren't necessary.
Here's a working JSFiddle. Cheers!

:Active links using javascript

Ok here is my dilemma. I have a header.php file that contains the header information (navigation and logo) I use that so that I can include the file in each my pages where it is needed and to make for easier editing. The issue I have is that I obviously cannot use :active to color or alter links text so the user knows what page they are on.
How can I achieve what I want with the way I am doing it, or am I stuck doing this the long way. Is there javascript that can do this.
Understand I am new to HTML and CSS and am looking for simple ways to change header and footer without having to edit every page individually.
Markos
I don't know how your html looks like, but for example if you have jQuery included and you are using absolute patches in links you could use something like this:
$('a[href="'+document.location.origin+document.location.pathname+'"]').css('color', '#f00');
or if you don't have jQuery and have absolute links you can use something like this:
var a = document.getElementsByTagName('a');
for (i in a) {
if (a[i].href == document.location.origin+document.location.pathname){
// red color
a[i].style.color = '#900'
}
}
Add below CSS to your code. Then apply class to your <a> tags.
1.
/*choose current(active) a tag which has class named niceClass*/
.niceClass a.current {color:red;}
2.
Link Title
Link Title2
...

create css class on the fly in codebehind

I have a search page that is used in multiple places with multiple 'themes' throughout my site. I have a few divs that can have their background color changed based on a radio button selection (whether they are enabled or not). I can do this just fine by changing the css class of the div on the fly with javascript.
However, these themes could potentially change, and the background color is grabbed from a database when the page is created. Right now I do this in the C# codebehind:
string bgStyle = "background-color:" +theme.searchTextHeaderColor +";";
OwnerSearchHeader.Attributes.Add("style", bgStyle);
In the Javascript I need to change this color to make it look disabled, and when the user clicks back to this div I need to re-enable it by changing it back to its original color. But since I only knew this color in the code-behind, I don't know what it was in the Javascript.
So my thought was to create a css class in the resulting HTML page when the page is loaded with the background color I need. Then I could simply switch from the divEnabled and divDisabled class in the javascript. But I'm not exactly sure how to do that.
Alternatively I could create a hidden element, assign it the 'enabled' style, and use that as a reference in the JavaScript when enabling my div. This seems like a hack but maybe its the easiest way. I'm still new to a lot of this, so I'd appreciate any suggestions. Thanks for the input!
So my thought was to create a css class in the resulting HTML page when the page is loaded with the background color I need. Then I could simply switch from the divEnabled and divDisabled class in the javascript. But I'm not exactly sure how to do that.
Yes, this is the anser; do this. In the <head> of your document add a <style> and put your CSS in there like so: (my Asp.NET is a little rusty so forgive me if it has some hicups ;) )
<style>
<!--
.divEnabled {
background-color:<%=theme.searchTextHeaderColor%>;
}
.divDisabled {
background-color:gray; /* or wtv */
}
-->
</style>
You could also put it in an external CSS file, which may be a good idea.
Then write some JavaScript to add/remove the class attribute (I'm going to ask that you don't call is the "CSS Class" ;) )
var ownersearchheader = document.getElementById("<%=OwnerSearchHeader.ClientId%>");
// changing the class attribute to `divDisabled`
var newClassAttribute = ownersearchheader.getAttribute("class").replace(/\bdivEnabled\b/, "divDisabled")
ownersearchheader.setAttribute("class", newClassAttribute);
// ... or,
// changing the class attribute to `divEnabled`
var newClassAttribute = ownersearchheader.getAttribute("class").replace(/\bdivDisabled\b/, "divEnabled")
ownersearchheader.setAttribute("class", newClassAttribute);
This is indeed a mouthfull, so, like #Haydar says, you might want to use jQuery, which offers easy-as-pie addClass(), removeClass() and toggleClass() methods.
You can use the jquery .toggleClass method.
Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
Here is the link to the api doc.
Jquery API

Categories