JavaScript toggle 2 links from full page - javascript

I have a page full of links and they're paired. What I would like to do is once I've clicked a question mark (for help) the first 2 pairs are selected, then the next 2 and so on. The problem is that the links are created randomly on the page. I have the following code which selects the first link and its pair.
$(".main .container a:first").css("color", "#0c0");
var valid = $(".main .container a:first").attr("class").split(" ");
var links = $(".main .container a");
for (i = 0; i < links.length; i ++) {
var attributes = $(links[i]).attr("class").split(" ");
if (attributes[1] == valid[1]) {
$(links[i]).eq(0).css("color", "#0c0");
}
}
EDIT:
$(".help a").on("click", function()
{
var unchecked = $(".main .container a:not(.selected)");
var valid = unchecked.eq(0).attr("class").split(" ");
var links = $(".main .container a");
unchecked.eq(0).addClass("selected");
for (i = 0; i < links.length; i ++) {
var attributes = $(links[i]).attr("class").split(" ");
if (attributes[1] == valid[1]) {
$(links[i]).eq(0).addClass("selected");
}
}
});

Looks like you can simply manage that by adding a CSS class to the elements that were already "selected".
Check this simple test I did at JSFiddle: http://jsfiddle.net/L4rUM/1/
// When you click the "?"
$('button#btnHelp').on('click', function(){
// Gathers the list of ALL <a> elements that were not "selected" yet
var uncheckeds = $('.main .container > a:not(.selected)');
// If you have at least 2 available elements
if(uncheckeds.size() > 1){
// Adds the .selected CSS class to first 2 non-selected elements
uncheckeds.eq(0).addClass('selected');
uncheckeds.eq(1).addClass('selected');
}
});
And the CSS manipulation you are doing is now controlled by just adding the CSS class:
.selected { color: #0c0; }
I hope this helps and solve your problem :)

Related

How to remove CSS classes from the classList of each div element, and assign a desired CSS class to a div element, in an array of div elements?

I have a set of HTML buttons programmed with JavaScript. There's a class assigned to an array of HTML div elements, and the buttons are supposed to change that class.
Here's the code for one of the buttons:
a4.addEventListener('click', function()
{
//makes sure all the other buttons aren't chosen
var button = document.getElementsByClassName('unchosen');
for (var i = 0; i < button.length; i++)
{
button[i].classList.remove('chosen');
}
a4.classList.add('chosen');
//is supposed to assign the new css class to every plate div element and get rid of the undesired classes
const plates = document.querySelectorAll(".assay1Plate", ".assay2Plate", ".assay3Plate", ".assay4Plate");
for (var i = 0; i < 35; i++)
{
if (plates[i].classList.contains == "assay1Plate")
{
plates[i].classList.remove("assay1Plate");
console.log("Removed assay 1 plate class due to assay 4 click");
}
if (plates[i].classList.contains == "assay2Plate")
{
plates[i].classList.remove("assay2Plate");
}
if (plates[i].classList.contains == "assay3Plate")
{
plates[i].classList.remove("assay3Plate");
}
plates[i].classList.add("assay4Plate");
//I was going to use this to remove undesired classes from the div elements... but it doesn't really work
/*
for(var k = 0; k < classes.length; k++)
{
if (plates[i].classList.contains(classes[k]) && classes[k] != "assay4Plate")
{
plates[i].classList.remove(classes[k]);
console.log("Classes removed save 4");
}
}
*/
}
});
Console.log shows that classes are being ADDED to the classList of the elements, but it doesn't seem like they can be removed once they've already been added. Clicking the first button changes their classes, clicking the second changes it again, clicking the third changes it again, and so on.... but then clicking the first or second buttons again does nothing.

How do i style each li element at a time?

I am trying to style each <li> element at a time on click, not all at once. For each click, the first one, then on the second click, the next one and so on...
This code puts style on all li elements at once. How do I do it?
$("a").click(function() {
var menu = document.getElementsByTagName("li");
for (var i = 0; menu[i]; i++) {
$(menu).css("background", "red");
}
});
p {
color: red;
margin: 5px;
cursor: pointer;
}
p:hover {
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a>sdadsa</a>
<ul>
<li>asda</li>
<li>sadada</li>
<li>sada</li>
<li>asdad</li>
</ul>
You can use jQuery's .css() to check the css value of specified element
$("a").click(function() {
var menu = document.getElementsByTagName("li");
for (var i = 0; menu[i]; i++) {
// get element of current index
const menuElement = menu[i];
// if the first element's background is not red.
if ($(menuElement).css("background") !== "red") {
// set it red.
$(menuElement).css("background", "red");
// escape for loop
break;
}
}
});
You can use a variable that points to current li element which should change background on the next click. When the anchor tag is clicked we remove the background of previous li element and change the current element's background
<script>
let current = 0;
$("a").click(function () {
var menu = document.getElementsByTagName("li");
let prev = current-1;
if(prev==-1) prev = menu.length-1;
menu[prev].style.background = "none";
menu[current].style.backgroud = "red";
current = (current + 1)%menu.length;
});
</script>
One approach would be to add a class to do the styling.
When you click your element find the first <li> that doesn't have that class and add it to that one.
Adding and removing classes is typically easier than modifying and undoing inline style
$("a").click(function() {
$('li').not('.red-bg').first().addClass('red-bg')
});
.red-bg {background:red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a>sdadsa</a>
<ul>
<li>asda</li>
<li>sadada</li>
<li>sada</li>
<li>asdad</li>
</ul>

Get an element id and generic element in JavaScript

I have a CSS selector #menu li {background-color: red;}.
I want to access its attributes in JavaScript. It's important that I need to access both #menu and li since #menu alone has different attributes. It seems like getElementById(menu li), QuerySelector and getComputedStyle are not working in this case.
Is there any other way to achieve that or am I missing something here?
You should use jQuery for this, here the easy code example
//html
<div id="menu" data-number="123" >
</div>
//jquery
var menu = $('#menu').attr('data-number');
console.log(menu);
//print 123
jquery version
https://jsfiddle.net/pn52uvw1/
$(".button_1").click(function(){
alert($("#menu").attr("data-item-id"));
})
$(".button_2").click(function(){
alert($("#menu li").attr("data-item-id"));
})
non jquery version
https://jsfiddle.net/pn52uvw1/2/
window.firstFunction = function(){
var target = document.getElementById("menu");
alert(target.getAttribute('data-item-id'));
}
window.secondFunction = function(){
var target = document.getElementById("menu").children[0];
alert(target.getAttribute('data-item-id'));
}
but you will need to get rid of that [0] index probably, and use a for or something for multiple li items
If you want to get that css rule's property, you can do like this:
function getStyleFromSelector(selector, styleName) {
// Get all style elements
var styles = document.styleSheets;
var styleIndex = 0, styleCount = styles.length;
var rules, ruleCount, ruleIndex;
// Iterate though styles
for (styleIndex = 0; styleIndex < styleCount; ++styleIndex) {
// Get the css rules under the style.
rules = styles[styleIndex].rules;
ruleCount = rules.length;
for (ruleIndex = 0; ruleIndex < ruleCount; ++ruleIndex) {
// Check if the selector match the one we want
if (rules[ruleIndex].selectorText === selector) {
return styleName ?
rules[ruleIndex].style.getPropertyValue(styleName) : rules[ruleIndex];
}
}
}
}
var div = document.getElementById("results");
var result = getStyleFromSelector('#menu li');
console.log(result);
div.innerHTML = 'background-color is : ' + result.style.backgroundColor;
console.log(getStyleFromSelector('#menu li', 'background-color'));
#menu li {background-color: red;}
<div id="results"></div>
You can try it without additional Libraries with the following
var len = document.querySelectorAll("#menu li").length;
for(i = 0; i<len; i++)
document.querySelectorAll("#menu li")[i].style.backgroundColor="blue";
I also made you (a not very beautiful) jsfiddle
https://jsfiddle.net/gmeewsmz/

jQuery addClass on user control list

I have a list on a user control and a jquery script that works when an li is clicked. This works fine. I want to change the class on the selected li but having trouble making this work. I tried this in a fiddle and no problem - but in my actual page - no good.
the fiddle is at https://jsfiddle.net/u6sykb8d/7/
the actual jquery script is
$(document).ready(function () {
$('.listButtons li').on("click", function () {
$('.selected').removeClass("selected");
$(this).addClass("selected");
var tabid = $(this).attr('id');
var cont = $(this).closest($(".container"));
var tabs = ["tabAddress", "tabPeople0", "tabPeople1", "tabPeople2", "tabPeople3", "tabPeople4"];
var divs = ["divAddress0", "divPeople_0", "divPeople_1", "divPeople_2", "divPeople_3", "divPeople_4"];
var indx = tabs.indexOf(tabid);
for (var i = 0; i < divs.length; i++) {
if (i == indx) {
cont.find($("div[id$='" + divs[i] + "']")).show();
}
else {
cont.find($("div[id$='" + divs[i] + "']")).hide();
}
}
});
});
the rest of the script works, the lines removing and adding the class don't seem to work.
Any ideas?
embarrassed to say but after digging through the code the problem turned out to be an extra space in the css file 'li .selected' instead of 'li.selected' . Thanks for the help

How to change menu li class when div changes

I'm working on a one-page site that has several "articles". Each div has class "article" and id "first", "second", "third", etc. I have a standard menu:
<ul id="nav">
<li id="n1"></li>
<li id="n2"></li>
<li id="n3"></li>
//...etc
</ul>
What I need to do is assign the class "active" to the li tag w/id n1 when the current article has id "first" (and unassign active class from all other li tags); assign active class to li tag w/id n2 when current article has id "second"; etc.
I would appreciate any help... I'm really stuck on this one. TIA for your help.
P.S. I'm using the following code to, in essence, assign an active class to the currently viewed article:
$('#first, #second, #third, ...).bind('inview', function (event, visible) {
if (visible == true) {
$(this).addClass("inview");
} else {
$(this).removeClass("inview");
}
});
There are more ways to do it. This is one, which may give you ideas:
var navrefs= document.getElementById('nav').getElementsByTagName('a');
for (var i=0, len = navrefs.length;i<len;i++){
if (location.hash == navrefs[i].href){
navrefs[i].parentNode.className = 'active';
} else {
navrefs[i].parentNode.className = '';
}
}
Here's an example of the following →
The following assumes you have the class current on your currently active article page:
var articles = document.getElementsByClassName('article'),
al = articles.length,
which, i;
for (i = 0; i < al; i++) {
if (/current/.test(articles[i].className)) {
which = articles[i].id;
}
}
var atags = document.getElementsByTagName('a'),
al2 = atags.length;
for (i = 0; i < al2; i++) {
if (atags[i].href.search(which) > -1) {
atags[i].parentNode.className = 'active';
} else {
atags[i].parentNode.className = '';
}
}
Since it's to achieve a CSS effect, why not just right CSS like this:
.first #n1,
.second #n2,
.third #n3,
...etc
{
CSS for active article
}
and then just make the JS in charge of setting the appropriate class on the wrapper/body, e.g.
<li id="n1"></li>
etc.
...
function setC(str){
document.getElementById('wrapper').className=str;
}
This would would reduce the demand on the JS engine

Categories