Adding class names on hover based on conditions - javascript

I've created a tabbed module which works by getting content that is in the .content div (which is hidden) and displaying it in a empty div called .overview.
The idea behind this tabbed module is that, on hover (or when class active exists), the content on the right will change based on what header is being selected from the left. I.e. If I hover over a header named "Red", the .overview div on the right will spit out "red".
However, the issues I'm having are the following:
In the demo below, don't hover on any of the headers. The .overview div has no content - which is obviously not ideal. If .tabs has class .active, then I want its content displayed on the right. I have a counter running which changes class active every 5 seconds. I don't only want to show stuff on hover.
Having said the above, if I hover over another tabs div, I want the counter to stop - to prevent it from adding class active to another .tabs div (because the hovered on tabs is active.
Demo:
$(document).ready(function() {
// add class .active on li hover
$('.tabs').mouseenter(function() {
//$('.tabs').removeClass('active');
$(this).parents('.tabs').addClass('active');
});
// Change active tab every x seconds
$(function() {
var list = $(".tabs"),
currentActive = 0;
time = 5; // interval in seconds
setInterval(function() {
currentActive = (currentActive + 1) % list.length;
list.removeClass('active').eq(currentActive).addClass('active');
}, time * 1000);
});
})
var overview = $('.overview');
$('.tabs').each(function(i) {
var thisTab = $(this);
var thisContent = thisTab.find('.content').html();
// when class .active exists, change content in .overview
if ($('.tabs').hasClass('active')) {
overview.html(thisContent);
}
// on hover, change content in .overview
thisTab.on('mouseenter', function(e) {
thisTab.addClass('active');
overview.html(thisContent);
})
.on('mouseleave', function(e) {
thisTab.removeClass('active');
overview.html('');
});
});
.tabs.active {
background: none yellow;
}
.list {
flex-basis: 40%;
}
.list li {
list-style-type: none;
}
.overview {
flex-basis: 60%;
border: 1px solid blue;
}
.content {
display: none;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex flex-row">
<div class="list">
<li class="tabs active">
<div class="header"><span>Header</span></div>
<div class="content">
<p>Content 1</p>
</div>
</li>
<li class="tabs">
<div class="header"><span>Header 2</span></div>
<div class="content">
<p>Content 2</p>
</div>
</li>
<li class="tabs">
<div class="header"><span>Header 3</span></div>
<div class="content">
<p>Content 3</p>
</div>
</li>
</div>
<div class="overview"> </div>
</div>
Edit:
I've managed to make some movement on issue 1. I've added:
if ($('.tabs').hasClass('active')) {
overview.html(thisContent);
}
Which now, without hover, displays content in .overview, however, the content doesn't change when another tab is .active (i.e. in the demo, don't hover over anything, wait and it just shows content 3 for all headers.

I would do the following (I have commented what I have changed)
$(document).ready(function() {
var list = $(".tabs"),
overview = $('.overview'),
autoInterval, // interval var
currentActive = 0; // make this global to this closure
overview.html(list.eq(0).find('.content').html()); // set overview content
startInterval(); // start interval straight away
// add class .active on li hover
list.mouseenter(function() {
var thisTab = $(this);
currentActive = list.index(this); // set current active
list.removeClass('active'); // remove active class
thisTab.addClass('active'); // add active class
clearInterval(autoInterval); // clear the interval whilst hovering
var thisContent = thisTab.find('.content').html(); // get content
overview.html(thisContent); // set overview content
});
list.mouseleave(function() {
startInterval(); // restart the interval on mouseleave
});
function startInterval() {
// Change active tab every x seconds
time = 5; // interval in seconds
autoInterval = setInterval(function() {
currentActive = (currentActive + 1) % list.length;
list.removeClass('active');
var currentTab = list.eq(currentActive);
currentTab.addClass('active');
overview.html(currentTab.find('.content').html()); // set overview content
}, time * 1000);
}
});
.tabs.active {
background: none yellow;
}
.list {
flex-basis: 40%;
}
.list li {
list-style-type: none;
}
.overview {
flex-basis: 60%;
border: 1px solid blue;
}
.content {
display: none;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex flex-row">
<div class="list">
<li class="tabs active">
<div class="header"><span>Header</span></div>
<div class="content">
<p>Content 1</p>
</div>
</li>
<li class="tabs">
<div class="header"><span>Header 2</span></div>
<div class="content">
<p>Content 2</p>
</div>
</li>
<li class="tabs">
<div class="header"><span>Header 3</span></div>
<div class="content">
<p>Content 3</p>
</div>
</li>
</div>
<div class="overview"> </div>
</div>

As soon as you add the mouseenter event, you need to stop the interval, you have the method clearInterval to do so.

Related

Two Column Accordion with Separate Full Width Divs

The intension is to have a two column accordion, without limiting the "expand" field to the left or right column. The catch is that there will be multiple on one page. This is already created, but only button 1 is working. With the way my JS is going, it will get very very repetitive - I am looking for assistance with re-writing the JS to be multiple click friendly. Fiddle: https://codepen.io/ttattini/pen/abLzaaY
EDIT: It would also be perfect if one dropdown would close as the next is opened
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="row">
<div id="column">
<button id="button">I am Button #1</button>
<button id="button">I am Button #3</button>
</div>
<div id="column">
<button id="button">I am Button #2</button>
<button id="button">I am Button #4</button>
</div>
</div>
<div id="hidden">
<p id="content"> So here I am #1</p>
</div>
<div id="hidden">
<p id="content"> So here I am #2</p>
</div>
<div id="hidden">
<p id="content"> So here I am #3</p>
</div>
<div id="hidden">
<p id="content"> So here I am #4</p>
</div>
CSS
#hidden {
background: #ccc;
margin-top: 2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
#button {
padding: 10px;
margin-top: 5px;
width:50%;
margin-left: 10%;
cursor: pointer;
}
#row {
display: flex;
}
#column {
flex: 50%;
}
JS
$(function() {
var b = $("#button");
var w = $("#hidden");
var l = $("#content");
b.click(function() {
if (w.hasClass('open')) {
w.removeClass('open');
w.height(0);
} else {
w.addClass('open');
w.height(l.outerHeight(true));
}
});
});
The biggest issue is that you're using IDs when you should be using classes. IDs must be unique to each element in a page. When you repeat an ID, JS will only target the first element using that ID. That's why only the first one is working.
The second issue is that, because of the way the script is written, it will only target a single element. What you need to do is get all the elements you want to target by something like their class name and then loop through them, applying the event listener to each one and its appropriate children.
EDIT: Here is an example from some code I wrote for a page with multiple accordions a few weeks ago in vanilla JS
//Below I establish a counting variable and find all the accordions on the page
const acc = document.getElementsByClassName( 'accordion' );
let i;
//Looping through each accordion
for ( i = 1; i <= acc.length; i++ ) {
//Identify target for the event listener. In this case, a heading for each accordion, which I've numbered e.g. "title-1"
const title = 'title-' + i;
const label = document.getElementById( title );
//Identify target content, in this case a list that has a unique ID e.g. "list-1"
const listNum = 'list-' + i;
const list = document.getElementById( listNum );
//Add event listener to heading that toggles the active classes
label.addEventListener( 'click', function() {
label.classList.toggle( 'accordion--active' );
});
}
Of course, there's more than one way to skin a cat, but this is a working example.
I have tracked the clicked event of each button and showed the corresponding hidden content with the use of data- attribute.
I have used vanilla JavaScipt instead of jQuery.
const buttons = document.querySelectorAll('.button');
const hiddens = document.querySelectorAll('.hidden');
buttons.forEach((btn) => {
btn.addEventListener('click', btnClicked)
function btnClicked(e) {
hiddens.forEach((hidden) => {
if(e.target.dataset.btn == hidden.dataset.content) {
hidden.classList.toggle('height')
} else {
hidden.classList.remove('height')
}
})
}
})
.hidden {
background: #ccc;
margin-top: 2%;
padding-left:2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
.hidden.height {
height: 50px;
}
.button {
padding: 10px;
color: white;
background-color: #2da6b5;
border: none;
margin-top: 5px;
width:90%;
margin-left: 5%;
cursor: pointer;
}
.button:hover {
filter: brightness(.9);
}
#row {
display: flex;
}
.column {
flex: 50%;
}
<div id="row">
<div class="column">
<button class="button" data-btn="one">I am Button #1</button>
<button class="button" data-btn="three">I am Button #3</button>
</div>
<div class="column">
<button class="button" data-btn="two">I am Button #2</button>
<button class="button" data-btn="four">I am Button #4</button>
</div>
</div>
<div class="hidden" data-content="one">
<p class="content"> So here I am #1</p>
</div>
<div class="hidden" data-content="two">
<p class="content"> So here I am #2</p>
</div>
<div class="hidden" data-content="three">
<p class="content"> So here I am #3</p>
</div>
<div class="hidden" data-content="four">
<p class="content"> So here I am #4</p>
</div>
Also, please do not use the same ID at multiple elements.

Javascript tabs using data attributes rather than IDs to link button and tab

I'm wanting to create a variation of Javascript tabs using data attributes rather than IDs to link the tab and the content.
Here's how it should work:
Clicking a <button class="tab" data-tab-trigger="1"> adds a class of is-active and removes any is-active classes from all other button elements
The value of data-tab-trigger matches the value of data-tab-content on the corresponding <div class="tab-content" data-tab-content="1"> and should add a class of is-open to it
The is-active class highlights the active tab and the is-open class shows the related tab content
Here's the JS I'm currently working which isn't working as expected:
var tabTriggerBtns = document.querySelectorAll('.tabs li button');
tabTriggerBtns.forEach(function(tabTriggerBtn, index){
tabTriggerBtn.addEventListener('click', function(){
var tabTrigger = this;
var tabTriggerData = tabTrigger.getAttribute('data-tab-trigger');
var tabContent = document.querySelector('.tab-content');
var currentTabData = document.querySelector('.tab-content[data-tab-content="' + tabTriggerData + '"]').classList.add('is-open');
if(tabContent !== currentTabData) {
tabContent.classList.toggle('is-open');
}
if(tabTrigger.classList.contains('is-active')) {
tabTrigger.classList.remove('is-active');
}
else {
tabTriggerBtn.classList.remove('is-active');
tabTrigger.classList.add('is-active');
}
});
});
Here's a Codepen with my ongoing script: https://codepen.io/abbasarezoo/pen/752f24fc896e6f9fcce8b590b64b37bc
I'm having difficulty finding what's going wrong here. I'm relatively comfortable writing jQuery, but quite raw when it comes to vanilla JS so any help would be very much appreciated.
One of your main issue is in this line:
tabContent !== currentTabData
You may use dataset in order to access data attributes.
Moreover, you may simplify your code in few steps:
remove classess
add classess
The snippet:
var tabTriggerBtns = document.querySelectorAll('.tabs li button');
tabTriggerBtns.forEach(function(tabTriggerBtn, index){
tabTriggerBtn.addEventListener('click', function(){
var currentTabData = document.querySelector('.tab-content[data-tab-content="' + this.dataset.tabTrigger + '"]');
// remove classess
document.querySelector('.tab-content.is-open').classList.remove('is-open');
document.querySelector('.tabs li button.is-active').classList.remove('is-active');
// add classes
currentTabData.classList.add('is-open');
this.classList.add('is-active');
});
});
* {
margin: 0;
padding: 0;
}
body {
display: flex;
}
.tabs {
width: 25%;
border: 2px solid red;
}
button.is-active {
background-color: red;
}
.tab-content__outer {
width: 75%;
}
.tab-content {
display: none;
}
.tab-content.is-open {
display: block;
background-color: yellow;
}
<ul class="tabs">
<li>
<button class="tab is-active" data-tab-trigger="1">First</button>
</li>
<li>
<button class="tab" data-tab-trigger="2">Second</button>
</li>
<li>
<button class="tab" data-tab-trigger="3">Third</button>
</li>
</ul>
<div class="tab-content__outer">
<div class="tab-content is-open" data-tab-content="1">
First
</div>
<div class="tab-content" data-tab-content="2">
Second
</div>
<div class="tab-content" data-tab-content="3">
Third
</div>
</div>

Show first navigation window by default until others clicked?

Currently, I am trying to hide Navigation when another button is clicked like below.
var $links = $('nav a');
var $content = $('.navLinks');
$links.click(function() {
$content.hide();
$content.eq( $links.index(this) ).show();
});
.navLinks {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
<nav>
1
2
3
</nav>
</div>
<div id="1" class="navLinks"> content 1 </div>
<p>Some dummy paragraph that's trying to break our index count :)</p>
<div id="2" class="navLinks"> content 2 </div>
<div id="3" class="navLinks"> content 3 </div>
However, I'd like for the results of 1 to be displayed until a user clicks on 2 or 3 how can I go about doing that?
Just add different styles for the first .navLinks element in css
.navLinks {
display: none;
}
.navLinks:first-of-type {
display: block;
}
EDIT
It won't work in this case.
:first-of-type would work if #1 div would be the first div, but is in fact second after .nav div.
So you can set style display: block for all .navLinks elements and set style display: none for all of those .navLinks elements that are after an element with class .navLinks.
Here is an working example
var $links = $('nav a');
var $content = $('.navLinks');
$links.click(function() {
$content.hide();
$content.eq( $links.index(this) ).show();
});
.navLinks {
display: block;
}
.navLinks ~ .navLinks {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
<nav>
1
2
3
</nav>
</div>
<div id="1" class="navLinks"> content 1 </div>
<p>Some dummy paragraph that's trying to break our index count :)</p>
<div id="2" class="navLinks"> content 2 </div>
<div id="3" class="navLinks"> content 3 </div>
Try this
$('#1').show();
var $links = $('nav a');
var $content = $('.navLinks');
$links.click(function() {
$content.hide();
$content.eq( $links.index(this) ).show();
});
Simply add css to show #1 (use ID's that starts with letters, not numbers) by default:
var $links = $('nav a');
var $content = $('.navLinks');
$links.click(function() {
$content.hide();
$content.eq( $links.index(this) ).show();
});
.navLinks {
display: none;
}
#a1 {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
<nav>
1
2
3
</nav>
</div>
<div id="a1" class="navLinks"> content 1 </div>
<p>Some dummy paragraph that's trying to break our index count :)</p>
<div id="a2" class="navLinks"> content 2 </div>
<div id="a3" class="navLinks"> content 3 </div>

Show/hide multiple Divs with links

I didn't clearly explain what I was trying to do. Hopefully this will be better.
Currently I'm using this Fiddle to toggle some divs. It acts as an accordion and shows only one div at a time. Clicking one of the titles will show the content of that div and clicking another title will hide the first div and show that one.
What I am having trouble with (and would like to do) is when opening one div I would like to hide access to the other divs until that first div is closed.
Meaning if I Click on "Content2" to show that content, I would like to hide access to Content1, Content3, and Content4 until Content 2 is closed again.
function ReverseDisplay(d) {
var els = document.querySelectorAll('.toggle.active:not(#' + d + ')');
for (var i = 0; i < els.length; i++) {
els[i].classList.remove('active');
}
document.getElementById(d).classList.toggle('active')
}
.toggle {
display: none;
}
.toggle.active {
display: block;
}
<a href="javascript:ReverseDisplay('content1')">
Content1
</a>
<a href="javascript:ReverseDisplay('content2')">
Content2
</a>
<a href="javascript:ReverseDisplay('content3')">
Content3
</a>
<a href="javascript:ReverseDisplay('content4')">
Content4
</a>
<div id="content1" class="toggle">
<p>Content 1 goes here.</p>
</div>
<div id="content2" class="toggle">
<p>Content 2 goes here.</p>
</div>
<div id="content3" class="toggle">
<p>Content 3 goes here.</p>
</div>
<div id="content4" class="toggle">
<p>Content 4 goes here.</p>
</div>
This should work... Use the id passed to identify the element and add class by checking if active exists.
function ReverseDisplay(d) {
var id = d
var el = document.getElementById(id)
var elClassList = el.classList
var [...active] = document.querySelectorAll('.toggle.active')
debugger
if (active.length === 0) {
el.classList.add('active')
} else if (id === active[0].id) {
el.classList.remove('active')
}
}
.toggle {
display: none;
margin-top: 40px;
}
.toggle.active {
display: block;
}
a {
position: fixed;
top: 10px;
}
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" class="toggle">
<p>Content 1 goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')" style="left:150px">
Click to show/hide.
</a>
<div id="uniquename1" class="toggle">
<p>Content 2 goes here.</p>
</div>
Use this javascript function in order to achieve accordion style behaviour, for as many links as you might want to have.
function ReverseDisplay(d) {
var els = document.getElementById(d);
if (els.classList.contains('active')){
els.classList.remove('active');
}else{
var activeDivs = document.getElementsByClassName('active');
for (var i = 0; i < activeDivs.length; i++) {
activeDivs[i].classList.remove('active');
}
els.classList.add('active');
}
}

accordion+tab = previous content does not disappear

When I click different links from different accordion elements content is displayed below previous one
$('.accordion').on('click', '.accordion-control', function(e){
e.preventDefault(); // Prevent default action of button
$(this) // Get the element the user clicked on
.next('.accordion-panel') // Select following panel
.not(':animated') // If it is not currently animating
.slideToggle(); // Use slide toggle to show or hide it
});
$('.tab-list').each(function(){ // Find lists of tabs
var $this = $(this); // Store this list
var $tab = $this.find('li.active'); // Get the active list item
var $link = $tab.find('a'); // Get link from active tab
var $panel = $($link.attr('href')); // Get active panel
$this.on('click', '.tab-control', function(e) { // When click on a tab
e.preventDefault(); // Prevent link behavior
var $link = $(this), // Store the current link
id = this.hash; // Get href of clicked tab
if (id && !$link.is('.active')) { // If not currently active
$panel.removeClass('active'); // Make panel inactive
$tab.removeClass('active'); // Make tab inactive
$panel = $(id).addClass('active'); // Make new panel active
$tab = $link.parent().addClass('active'); // Make new tab active
}
});
});
When I click different links from different accordion elements content is displayed below previous one
/********** ACCORDION **********/
.accordion, .menu {
background-color: #f2f2f2;
color: #666;
margin: 0;
padding: 0;
overflow: auto;}
.accordion li {
padding: 0;
list-style-type: none;}
.accordion-control {
background-color: rgba(0,0,0,0);
color: red;
display: block;
width: 100%;
padding: 0.5em 0.5em 0.5em 0.7em;
margin: 0;
}
.accordion-panel {
display: none;
}
.accordion-panel p {
margin: 20px;
}
.accordion-panel img {
display: block;
clear: left;
}
/*************** Panels ***************/
.tab-panel {
display: none;
}
.tab-panel.active {
display: block;
}
How do I make the previous content disappear?
<ul class="accordion">
<li class="active"><a class="tab-control" href="#tab-0">Misc Features</a></li>
<li>
<button class="accordion-control">Armory</button>
<div class="accordion-panel">
<ul class="tab-list">
<li><a class="tab-control" href="#tab-1">S grade</a></li>
<li><a class="tab-control" href="#tab-2">A grade</a></li>
<li><a class="tab-control" href="#tab-3">B grade</a></li>
<li><a class="tab-control" href="#tab-4">C grade</a></li>
</ul>
</div>
</li>
<li>
<button class="accordion-control">Weaponry</button>
<div class="accordion-panel">
<ul class="tab-list">
<li><a class="tab-control" href="#tab-5">Special Ability</a></li>
</ul>
</div>
</li>
<li>
<button class="accordion-control">Jewelry</button>
<div class="accordion-panel">
<ul class="tab-list">
<li><a class="tab-control" href="#tab-6">Raid Boss Jewelry</a></li>
</ul>
</div>
</li>
</ul>
<div class="content"> <!-- Content -->
<div class="tab-panel active" id="tab-0">misc features</div>
<div class="tab-panel" id="tab-1">armor S</div>
<div class="tab-panel" id="tab-2">armor A</div>
<div class="tab-panel" id="tab-3">armor B</div>
<div class="tab-panel" id="tab-4">armor C</div>
<div class="tab-panel" id="tab-5">weapon SA</div>
<div class="tab-panel" id="tab-6">RB jewelry</div>
</div>
Here is how you can do this:
$('.accordion .accordion-panel').not(this).slideUp();
$(this) // Get the element the user clicked on
.next('.accordion-panel') // Select following panel
.not(':animated') // If it is not currently animating
.slideToggle(); // Use slide toggle to show or hide it
Here is the demo.
Reference: jQuery: exclude $(this) from selector

Categories