How to make accordion menu is open by default - javascript

const accordion = document.querySelector('.accordion');
const items = accordion.querySelectorAll('.accordion__item');
items.forEach((item) => {
const title = item.querySelector('.accordion__title');
title.addEventListener('click', (e) => {
const opened_item = accordion.querySelector('.is-open');
toggle_item(item);
if (opened_item && opened_item !== item) {
toggle_item(opened_item);
}
});
});
const toggle_item = (item) => {
const body = item.querySelector('.accordion__body');
const content = item.querySelector('.accordion__content');
if (item.classList.contains('is-open')) {
body.removeAttribute('style');
item.classList.remove('is-open');
}else {
body.style.height = body.scrollHeight + 'px';
item.classList.add('is-open');
}
}
.accordion__title {
background: gold;
}
.accordion__body {
border-radius: 5px;
height: 0;
overflow: hidden;
transition: height 0.3s ease-in-out;
}
<div class="accordion">
<div class="accordion__item">
<div class="accordion__title">Lorem ipsum dolor sit</div>
<div class="accordion__body">
<div class="accordion__content">
<ul>
<li>
x
</li>
</ul>
</div>
</div>
</div>
</div>
How can I edit this code to be opened by default without clicking on it when the page loaded? Code has 1 item now but I will add more items and I want to choose which item is open when the page loaded first.
I tried to do some changes but couldnt be successful with my poor javascript knowledge

Just add is-open class to the item you want it to be opened by default
<div class="accordion__item is-open">
and add this inital style for is-open class
.is-open .accordion__body {
height: 50px; // Or whatever inital value you want
}

You can just call the toggle_item function once at the initialization of the code, this way it will toggle from closed to opened:
const accordion = document.querySelector('.accordion');
const items = accordion.querySelectorAll('.accordion__item');
items.forEach((item) => {
const title = item.querySelector('.accordion__title');
title.addEventListener('click', (e) => {
const opened_item = accordion.querySelector('.is-open');
toggle_item(item);
if (opened_item && opened_item !== item) {
toggle_item(opened_item);
}
});
});
const toggle_item = (item) => {
const body = item.querySelector('.accordion__body');
const content = item.querySelector('.accordion__content');
if (item.classList.contains('is-open')) {
body.removeAttribute('style');
item.classList.remove('is-open');
}else {
body.style.height = body.scrollHeight + 'px';
item.classList.add('is-open');
}
}
toggle_item(items[0]);
.accordion__title {
background: gold;
}
.accordion__body {
border-radius: 5px;
height: 0;
overflow: hidden;
transition: height 0.3s ease-in-out;
}
<div class="accordion">
<div class="accordion__item">
<div class="accordion__title">Lorem ipsum dolor sit</div>
<div class="accordion__body">
<div class="accordion__content">
<ul>
<li>
x
</li>
</ul>
</div>
</div>
</div>
</div>

You need to call toggle_item function when index is zero in foreach loop.
const accordion = document.querySelector('.accordion');
const items = accordion.querySelectorAll('.accordion__item');
const toggle_item = (item) => {
const body = item.querySelector('.accordion__body');
const content = item.querySelector('.accordion__content');
if (item.classList.contains('is-open')) {
body.removeAttribute('style');
item.classList.remove('is-open');
}else {
body.style.height = body.scrollHeight + 'px';
item.classList.add('is-open');
}
}
items.forEach((item, index) => {
const title = item.querySelector('.accordion__title');
if(index==0){
toggle_item(item);
}
title.addEventListener('click', (e) => {
const opened_item = accordion.querySelector('.is-open');
toggle_item(item);
if (opened_item && opened_item !== item) {
toggle_item(opened_item);
}
});
});
.container{
max-width: 800px;
margin: 0px auto;
}
.accordion__title {
background: gold;
}
.accordion__item{
position: relative;
border:1px solid #f0f0f0;
margin-top: 10px;
cursor:pointer;
}
.is-open .accordion__body{
margin:10px 0;
}
.accordion__title{
padding:5px 0;
}
.accordion__close{
position: absolute;
right:0px;
top:-10px;
}
.accordion__close li{
list-style: none
}
.accordion__body {
border-radius: 5px;
height: 0;
overflow: hidden;
transition: height 0.3s ease-in-out;
}
<div class="container">
<div class="accordion">
<div class="accordion__item">
<div class="accordion__title">Lorem ipsum dolor sit</div>
<div class="accordion__body">
<div class="accordion__content">
sdsdsdsdsd
</div>
</div>
<ul class="accordion__close">
<li>x</li>
</ul>
</div>
<div class="accordion__item">
<div class="accordion__title">Lorem ipsum dolor sit</div>
<div class="accordion__body">
<div class="accordion__content">
sdsdsdsdsd
</div>
</div>
<ul class="accordion__close">
<li>x</li>
</ul>
</div>
<div class="accordion__item">
<div class="accordion__title">Lorem ipsum dolor sit</div>
<div class="accordion__body">
<div class="accordion__content">
sdsdsdsdsd
</div>
</div>
<ul class="accordion__close">
<li>x</li>
</ul>
</div>
</div>
</div>

You just need to select the item through the NodeList generated and then assign the is-open class to it through classList. The last change should be in CSS to select the accordion__body of the is-open class. Please check the comments to see the changes.
const accordion = document.querySelector('.accordion');
const items = accordion.querySelectorAll('.accordion__item');
const openedItem = items[1]; // Change the value to select the item. This selects the 2nd element since it starts from 0.
items.forEach((item) => {
openedItem.classList.add("is-open"); // Add class to the open item.
const title = item.querySelector('.accordion__title');
title.addEventListener('click', (e) => {
const opened_item = accordion.querySelector('.is-open');
toggle_item(item);
if (opened_item && opened_item !== item) {
toggle_item(opened_item);
}
});
});
const toggle_item = (item) => {
const body = item.querySelector('.accordion__body');
const content = item.querySelector('.accordion__content');
if (item.classList.contains('is-open')) {
body.removeAttribute('style');
item.classList.remove('is-open');
} else {
body.style.height = body.scrollHeight + 'px';
item.classList.add('is-open');
}
}
.accordion__title {
background: gold;
}
.accordion__body {
border-radius: 5px;
height: 0;
overflow: hidden;
transition: height 0.3s ease-in-out;
}
.is-open .accordion__body { /* Display the opened item */
height: 100%;
}
<div class="accordion">
<div class="accordion__item">
<div class="accordion__title">Item 1</div>
<div class="accordion__body">
<div class="accordion__content">
<ul>
<li>
Hero can be anyone. Even a man knowing something as simple and reassuring as putting a coat around a young boy shoulders to let him know the world hadn't ended. Well, you see... I'm buying this hotel and setting some new rules about the pool area.
I'm Batman Someone like you. Someone who'll rattle the cages. No guns, no killing. The first time I stole so that I wouldn't starve, yes. I lost many assumptions about the simple nature of right and wrong. And when I traveled I learned the fear before a crime and the thrill of success. But I never became one of them.
Hero can be anyone. Even a man knowing something as simple and reassuring as putting a coat around a young boy shoulders to let him know the world hadn't ended. Someone like you. Someone who'll rattle the cages.
Does it come in black? Bats frighten me. It's time my enemies shared my dread. I will go back to Gotham and I will fight men Iike this but I will not become an executioner.
</li>
</ul>
</div>
</div>
</div>
<div class="accordion__item">
<div class="accordion__title">Item 2</div>
<div class="accordion__body">
<div class="accordion__content">
<ul>
<li>
Click on the first element, Robin!
</li>
</ul>
</div>
</div>
</div>
<div class="accordion__item">
<div class="accordion__title">Item 3</div>
<div class="accordion__body">
<div class="accordion__content">
<ul>
<li>
x3
</li>
</ul>
</div>
</div>
</div>
</div>

Related

How do I check whether an element is already bound to an event?

Goal
Avoid unnecessary event bindings.
Sample code
Comment box with a reply button for each individual comment
const btns = document.getElementsByClassName('reply-btn');
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', showCommentContentAsPreview);
}
function showCommentContentAsPreview(e) {
console.log('showCommentContentAsPreview()');
// CHECK IF THIS BUTTON ALREADY BINDED !!!
const previewDiv = document.getElementById('preview');
const commentId = e.target.getAttribute('data-comment-id')
const commentDiv = document.getElementById('comment-' + commentId);
const commentText = commentDiv.querySelector('p').innerText
const closeReplyBtn = previewDiv.querySelector('button');
const previewContent = previewDiv.querySelector('.preview-content');
// set to preview
previewContent.innerText = commentText;
// show reply close button
closeReplyBtn.classList.remove('hidden');
// bind EventListener to "reply close button"
closeReplyBtn.addEventListener('click', closeReply)
function closeReply() {
console.log('bind to btn');
previewContent.innerText = '';
this.removeEventListener('click', closeReply);
closeReplyBtn.classList.add('hidden');
}
}
.hidden {
display: none;
}
.comment {
border-bottom: 1px solid #000;
padding: 5px;
}
.preview {
background-color: #ccc;
padding: 20px;
margin-top: 20px;
}
<div>
<!-- comment list -->
<div id="comment-1" class="comment">
<p>Comment Content 1</p>
<button class="reply-btn" data-comment-id="1">reply</button>
</div>
<div id="comment-2" class="comment">
<p>Comment Content 2</p>
<button class="reply-btn" data-comment-id="2">reply</button>
</div>
</div>
<!-- output -->
<div>
<div id="preview" class="preview">
<div class="preview-content"></div>
<button class="hidden">Close Preview</button>
</div>
</div>
Simulate problem
When you try the example, the following two scenarios occur:
Click reply once and then click "close preview"
Click on reply several times and then on "close preview".
Question
How can I avoid multiple bindings to the same button? I am already thinking about singleton.
Instead of binding a listener to every element in the series, you can bind a single listener once on a common parent of them all, and then use element.matches() to determine if the click target is the one that you want before doing more work. See the following example:
function logTextContent (elm) {
console.log(elm.textContent);
}
function handleClick (ev) {
if (ev.target.matches('.item')) {
logTextContent(ev.target);
}
}
document.querySelector('ul.list').addEventListener('click', handleClick);
<ul class="list">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
<li class="item">Item 4</li>
<li class="item">Item 5</li>
</ul>
With the helpful hints from #Zephyr and #jsejcksn I have rewritten the code of the above question. Thus I have achieved my goal of avoiding multiple identical bindings to one element.
const container = document.getElementById('comment-container');
const previewDiv = document.getElementById('preview');
const closeReplyBtn = previewDiv.querySelector('button');
const previewContent = previewDiv.querySelector('.preview-content');
container.addEventListener('click', handleClick);
function handleClick(ev) {
if (ev.target.matches('.reply-btn')) {
if (ev.target.getAttribute('listener') !== 'true') {
removeOtherListenerFlags();
ev.target.setAttribute('listener', 'true');
showCommentContentAsPreview(ev);
}
}
if (ev.target.matches('#preview button')) {
previewContent.innerText = '';
closeReplyBtn.classList.add('hidden');
removeOtherListenerFlags();
}
}
function showCommentContentAsPreview(e) {
console.log('showCommentContentAsPreview()');
const commentId = e.target.getAttribute('data-comment-id')
const commentDiv = document.getElementById('comment-' + commentId);
const commentText = commentDiv.querySelector('p').innerText
// set to preview
previewContent.innerText = commentText;
// show reply close button
closeReplyBtn.classList.remove('hidden');
}
function removeOtherListenerFlags() {
const replyBtns = container.querySelectorAll('.reply-btn')
Object.keys(replyBtns).forEach((el) => {
replyBtns[el].removeAttribute('listener');
})
}
.hidden {
display: none;
}
.comment {
border-bottom: 1px solid #000;
padding: 5px;
}
.preview {
background-color: #ccc;
padding: 20px;
margin-top: 20px;
}
<div id="comment-container">
<div id="comment-listing">
<!-- comment list -->
<div id="comment-1" class="comment">
<p>Comment Content 1</p>
<button class="reply-btn" data-comment-id="1">reply 1</button>
</div>
<div id="comment-2" class="comment">
<p>Comment Content 2</p>
<button class="reply-btn" data-comment-id="2">reply 2</button>
</div>
</div>
<!-- output -->
<div>
<div id="preview" class="preview">
<div class="preview-content"></div>
<button class="hidden">Close Preview</button>
</div>
</div>
</div>
Cool and Thanks!

Modal Window on card click JS CSS PHP

So I have 6 cards on my html. Each one on click need to pop up a modal window (this modal window is the card with more informations, so each modal window is corresponding to one card).
I dont know how to do that. After a day searching on the web I'm here to ask your help.
I have tried to make the html animal_card, and my modal appart. Then all the content will change with php.
And the Javascript need to change the modal window css property to absolute on click.
Someone know how to do that with Javascript ?
HTML :
<div class="animal_card">
<div class="card_title">
<h3>title</h3>
</div>
<div class="card_image">
<img src="image.img" alt="">
</div>
<div class="card_text">
<div class="card_info">
<div class="card_info_age">
<h4>Age</h4>
<p>14</p>
</div>
<div class="card_info_gender">
<h4>Gender :</h4>
<p>Female</p>
</div>
</div>
<h4>Who am I</h4>
<p>Description Text</p>
</div>
</div>
<div class="bg-modal">
<div class="modal-content">
<div class="modal-animal">
<h1>Animal Name</h1>
<button class="close" onclick="closeModal()">&times</button>
<div><img src="img/greciaprofile.jpg" alt=""></div>
<div class="animal-informations">
<div class="left">
<label for="">Age</label>
<p>14</p>
<label for="">Sexe</label>
<p>Female</p>
</div>
<div class="right">
<label for="">Description</label>
<p>
Text
</p>
</div>
</div>
<div>
<button class="main">Adopt</button>
<button class="secondary">Support</button>
</div>
</div>
</div>
</div>
CSS :
.bg-modal {
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.7);
position: absolute;
top: 0;
left: 0;
display: flex;
justify-content: center;
}
.modal-content {
position: absolute;
margin-top: 5rem;
width: 75vw;
background-color: $white;
border-radius: 15px;
}
Javascript :
const cards = document.querySelectorAll('.animal_card');
const modal = document.getElementsByClassName('bg-modal');
const onCardClick = async (e) => {
const card = e.currentTarget;
modal.style.position = 'absolute';
}
cards.forEach(card => card.addEventListener('click', onCardClick));
function closeModal() {
modal[0].style.position = 'none';
}
const cards = document.querySelectorAll('.animal_card');
const modal = document.getElementsByClassName('bg-modal');
const getKeyMap = (modal) => {
if (modal) {
let i;
let keyMap = {};
for (i = 0; i < modal.length; i++) {
const item = modal[i];
const key = item.getAttribute('key');
keyMap[key] = item;
}
return keyMap;
}
return null;
};
const modalMap = getKeyMap(modal);
const onCardClick = async (e) => {
const card = e.currentTarget && e.currentTarget.getAttribute('key') || null;
const selectedModal = modalMap[card] || null;
if (selectedModal) {
selectedModal.style.position = 'absolute';
}
}
cards.forEach(card => card.addEventListener('click', onCardClick));
.bg-modal {
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.7);
/* position: absolute; */
top: 0;
left: 0;
display: flex;
justify-content: center;
}
.modal-content {
position: absolute;
margin-top: 5rem;
width: 75vw;
background-color: $white;
border-radius: 15px;
}
<div key="5" class="animal_card">
<div class="card_title">
<h3>title</h3>
</div>
<div class="card_image">
<img src="image.img" alt="">
</div>
<div class="card_text">
<div class="card_info">
<div class="card_info_age">
<h4>Age</h4>
<p>14</p>
</div>
<div class="card_info_gender">
<h4>Gender :</h4>
<p>Female</p>
</div>
</div>
<h4>Who am I</h4>
<p>Description Text</p>
</div>
</div>
<div class="bg-modal" key="5">
<div class="modal-content">
<div class="modal-animal">
<h1>Animal Name</h1>
<button class="close">&times</button>
<div><img src="img/greciaprofile.jpg" alt=""></div>
<div class="animal-informations">
<div class="left">
<label for="">Age</label>
<p>14</p>
<label for="">Sexe</label>
<p>Female</p>
</div>
<div class="right">
<label for="">Description</label>
<p>
Text
</p>
</div>
</div>
<div>
<button class="main">Adopt</button>
<button class="secondary">Support</button>
</div>
</div>
</div>
</div>
So the direct answer using your example is modal on the onCardClick is returning a collection, not a single element. So selecting the first one modal[0] will fix the position update. I attached an example.
If you are going to show different modals based on the card you click on, you generally need to have a method to track them. Really depends on how you want to do that, based on ids, or index position or so on. Anyways, let me know if this helps.

How to make tabs with pure JS? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
i'am trying to do a "tab" menu with only pure JS CSS and HTML, where basically i have 7 divs with content and 7 "buttons" which should open the matching div. The strategy i want to use is to put all the divs with the "hidden" or the "Display: none" attribute stacked in the same spot and then, when i click on button it turns it´s matching div to visible. The problem i am facing is how to tell the button which div it should open (using arrays instead of doing it manually), and how to set it back to invisible when i click in other div (i was thinking about an if() that just turns on the visibility if the number of the button selected matches the number of the div, but supposedly every button has a div, so i am confused).
I think you want something like this?
document.addEventListener('click', ({ target: { dataset: { id = '' }}}) => {
if (id.length > 0) {
document.querySelectorAll('.tab').forEach(t => t.classList.add('hidden'));
document.querySelector(`#${id}`).classList.remove('hidden');
}
});
.hidden {
display:none;
}
<button data-id="tab1">tab 1</button>
<button data-id="tab2">tab 2</button>
<div id="tab1" class="tab">Tab 1</div>
<div id="tab2" class="tab hidden">Tab 2</div>
But the reality is we probably don't want to actually use button.
So lets change that up.
const tabClick = ({ target }) => {
const { dataset: { id = '' }} = target;
document.querySelectorAll('.tab').forEach(t => t.classList.remove('selected'));
target.classList.add('selected');
document.querySelectorAll('.tab-panel').forEach(t => t.classList.add('hidden'));
document.querySelector(`#${id}`).classList.remove('hidden');
};
const bindTabs = () => {
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', tabClick);
})
};
// Belts and braces, lets ensure our DOM is loaded and only assign click to the `tabs`
document.addEventListener('DOMContentLoaded', () => {
bindTabs();
});
.tab {
display: inline-block;
background-color: grey;
padding: 0.75rem;
color: #fff;
}
.selected {
background-color: black;
}
.tab-panel {
border: 2px solid black;
min-height: 50px;
max-width: 250px;
padding: 1rem;
}
.hidden {
display:none;
}
<div data-id="tab1" class="tab selected">tab 1</div>
<div data-id="tab2" class="tab">tab 2</div>
<div data-id="tab3" class="tab">tab 3</div>
<div data-id="tab4" class="tab">tab 4</div>
<div id="tab1" class="tab-panel">Tab 1</div>
<div id="tab2" class="tab-panel hidden">Tab 2</div>
<div id="tab3" class="tab-panel hidden">Tab 3</div>
<div id="tab4" class="tab-panel hidden">Tab 4</div>
So how can we approach this with basic javascript.
const tabCount = 4; // If we add a new tab, increase.
const tabClick = (event) => {
const tabButtonClicked = event.target;
const id = event.target.dataset.id;
// First remove selected and hide all tabs
for(let i = 1; i <= tabCount; i++) {
let tabButtonID = "#tabButton" + i;
let tabButton = document.querySelector(tabButtonID);
let tabID = "#" + tabButton.dataset.id;
let tab = document.querySelector(tabID);
tabButton.classList.remove("selected");
tab.classList.add("hidden");
}
// Now we set selected and show the selected tab.
document.querySelector("#" + id).classList.remove("hidden");
tabButtonClicked.classList.add("selected");
};
const bindTabs = () => {
// Loop through number of tabs and add a click event.
for(let i = 1; i <= tabCount; i++) {
let tabButtonID = "#tabButton" + i;
let tabButton = document.querySelector(tabButtonID);
tabButton.addEventListener('click', tabClick);
}
};
// Belts and braces, lets ensure our DOM is loaded and only assign click to the `tabs`
document.addEventListener('DOMContentLoaded', () => {
bindTabs();
});
.tab {
display: inline-block;
background-color: grey;
padding: 0.75rem;
color: #fff;
}
.selected {
background-color: black;
}
.tab-panel {
border: 2px solid black;
min-height: 50px;
max-width: 250px;
padding: 1rem;
}
.hidden {
display:none;
}
<div id="tabButton1" data-id="tab1" class="tab selected">tab 1</div>
<div id="tabButton2" data-id="tab2" class="tab">tab 2</div>
<div id="tabButton3" data-id="tab3" class="tab">tab 3</div>
<div id="tabButton4" data-id="tab4" class="tab">tab 4</div>
<div id="tab1" class="tab-panel">Tab 1</div>
<div id="tab2" class="tab-panel hidden">Tab 2</div>
<div id="tab3" class="tab-panel hidden">Tab 3</div>
<div id="tab4" class="tab-panel hidden">Tab 4</div>

Menu slider with javascript/jquery

I'm trying to make a menu slider for a restaurant with two clickable menus, the lunch menu and the dinner menu. I don't want the menus opening in a new window, just a clean click and the wanted menu opens.
Here is the code I have so far, I know it needs a lot of work, I'm new to the javascript/jQuery world. Pure javascript would be cool but anything jQuery would work too.
If someone can help me and please explain what needs to be fixed so i can understand this more I would greatly appreciate it. Thank You. On codepen
let lunchContainer = document.querySelectorAll('div.lunchmenu');
dinnerContainer = document.querySelectorAll('div.dinnermenu');
function reset() {
for(let i = 0; i < lunchContainer.length; i++) {
lunchContainer[i].style.display = 'none';
dinnerContainer[i].style.display = 'none';
}
};
$('.lunch').click(function(event) {
reset();
$('.lunchmenu').addClass('active');
lunchContainer.style.display = 'block';
});
$('.dinner').click(function() {
reset();
$('.lunchmenu').removeClass('active');
});
$('.dinner').click(function(event) {
reset();
$('.dinnermenu').addClass('active');
// dinnerContainer.style.display = 'block';
});
$('.lunch').click(function() {
reset();
$('.dinnermenu').removeClass('active');
// dinnerContainer.style.display = 'block';
});
<div class="page">
<div class="header">
<div class="logoHeader">
<a href="index.html" >
<img class="crab" src="http://images.all-free-download.com/images/graphicthumb/vivid_hand_drawn_crab_decoration_pattern_vector_551463.jpg " alt="KingChef Krab logo">
</a>
<h1 id="titleHeader">
King Chef
</h1>
</div>
<nav class="menuHeader">
<a class="specMenu" href="about.html">about</a></li>
<a class="specMenu" href="team.html">team</a></li>
<a class="specMenu" href="menus/dinner.html">menu</a></li>
<a class="specMenu" href="#">news</a></li>
<a class="specMenu" href="#">hours</a></li>
<a class="lastMenu" href="#">reservations</a></li>
</nav>
</div>
<nav id="menuCategory">
<a class="menuStyles lunch" href="#lunch">lunch</a>
<a class="menuStyles dinner" href="#dinner">dinner</a>
</nav>
<div class="container">
<div class="lunchmenu">
<p>hehehfdsafhkalfj</p>
</div>
<div class="dinnermenu">
<p>hdhfsahf</p>
</div>
</div>
</div>
.lunchmenu {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
&.active {
display: block;
}
}
.dinnermenu {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
&.active {
display: block;
}
}
Notice how much code I removed! You don't need to set display if you're going to use an 'active' class to do that job and you don't need to define the behavior of a click on your buttons twice.
Also, if each menu has a container, you don't need to iterate over all the items inside of them to set their display to none, setting the parent container to none will suffice.
Hope that helps!
let lunchContainer = document.querySelectorAll('.lunchmenu'), // notice ',' instead of ';'
dinnerContainer = document.querySelectorAll('.dinnermenu');
$('.lunch').click(function(event) {
$('.dinnermenu').removeClass('active');
$('.lunchmenu').addClass('active');
});
$('.dinner').click(function() {
$('.lunchmenu').removeClass('active');
$('.dinnermenu').addClass('active');
});
.lunchmenu, .dinnermenu {
display:none;
}
.active {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="lunch">lunch</button>
<button class="dinner">dinner</button>
<div class="lunchmenu">
<h5>lunch menu yayyy</h5>
<p>item lunch 1</p>
<p>item lunch 2</p>
</div>
<div class="dinnermenu">
<h5>Dinner menu yayyy</h5>
<p>itemdinner 1</p>
<p>item dinner 2</p>
</div>

jquery number count to a target number and pop display on click

I have a website : my website
i have built a jQuery counter to count up to a target number for the points in the team.Plz click on team tab.
problem :
when I load the page,the jquery point count works fine.Lets say when you go to team section and refresh the page.But when I scroll to through the various sections and reach team section,the effect doesnot show up.It looks like normal numbers.Can it be made possible,when the user scrolls to the "team" section the number count with the effect shows up.
The code for that part :
(function ($) {
$.fn.countTo = function (options) {
options = options || {};
return $(this).each(function () {
// set options for current element
var settings = $.extend({}, $.fn.countTo.defaults, {
from: $(this).data('from'),
to: $(this).data('to'),
speed: $(this).data('speed'),
refreshInterval: $(this).data('refresh-interval'),
decimals: $(this).data('decimals')
}, options);
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(settings.speed / settings.refreshInterval),
increment = (settings.to - settings.from) / loops;
// references & variables that will change with each update
var self = this,
$self = $(this),
loopCount = 0,
value = settings.from,
data = $self.data('countTo') || {};
$self.data('countTo', data);
// if an existing interval can be found, clear it first
if (data.interval) {
clearInterval(data.interval);
}
data.interval = setInterval(updateTimer, settings.refreshInterval);
// initialize the element with the starting value
render(value);
function updateTimer() {
value += increment;
loopCount++;
render(value);
if (typeof(settings.onUpdate) == 'function') {
settings.onUpdate.call(self, value);
}
if (loopCount >= loops) {
// remove the interval
$self.removeData('countTo');
clearInterval(data.interval);
value = settings.to;
if (typeof(settings.onComplete) == 'function') {
settings.onComplete.call(self, value);
}
}
}
function render(value) {
var formattedValue = settings.formatter.call(self, value, settings);
$self.html(formattedValue);
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 0, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
formatter: formatter, // handler for formatting the value before rendering
onUpdate: null, // callback method for every time the element is updated
onComplete: null // callback method for when the element finishes updating
};
function formatter(value, settings) {
return value.toFixed(settings.decimals);
}
}(jQuery));
jQuery(function ($) {
// custom formatting example
$('#count-number').data('countToOptions', {
formatter: function (value, options) {
return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
}
});
// start all the timers
$('.timer').each(count);
function count(options) {
var $this = $(this);
options = $.extend({}, options || {}, $this.data('countToOptions') || {});
$this.countTo(options);
}
});
body {
font-family: Arial;
padding: 25px;
background-color: #f5f5f5;
color: #808080;
text-align: center;
}
/*-=-=-=-=-=-=-=-=-=-=-=- */
/* Column Grids */
/*-=-=-=-=-=-=-=-=-=-=-=- */
.team-leader-box {
.col_half { width: 49%; }
.col_third { width: 32%; }
.col_fourth { width: 23.5%; }
.col_fifth { width: 18.4%; }
.col_sixth { width: 15%; }
.col_three_fourth { width: 74.5%;}
.col_twothird{ width: 66%;}
.col_half,
.col_third,
.col_twothird,
.col_fourth,
.col_three_fourth,
.col_fifth{
position: relative;
display:inline;
display: inline-block;
float: left;
margin-right: 2%;
margin-bottom: 20px;
}
.end { margin-right: 0 !important; }
/* Column Grids End */
.wrapper { width: 980px; margin: 30px auto; position: relative;}
.counter { background-color: #808080; padding: 10px 0; border-radius: 5px;}
.count-title { font-size: 40px; font-weight: normal; margin-top: 10px; margin-bottom: 0; text-align: center; }
.count-text { font-size: 13px; font-weight: normal; margin-top: 10px; margin-bottom: 0; text-align: center; }
.fa-2x { margin: 0 auto; float: none; display: table; color: #4ad1e5; }
}
.counter.col_fourth {
background-color: #fff ;
border-radius: 10px;
}
<section class="main-section team" id="team"><!--main-section team-start-->
<div class="container">
<h2>team</h2>
<h6>Take a closer look into our amazing team. We won’t bite.</h6>
<div class="team-leader-block clearfix">
<div class="team-leader-box">
<div class="team-leader wow fadeInDown delay-03s">
<div class="team-leader-shadow"></div>
<img src="img/team-leader-pic1.jpg" alt="">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div class="wrapper wow fadeInDown delay-05s">
<div class="counter col_fourth">
<i class="fa fa-check fa-2x"></i>
<h2 class="timer count-title" id="count-number" data-to="50" data-speed="1500"></h2>
<p class="count-text ">points</p>
<p1>click to know</p1>
</div>
</div>
</div>
<div class="team-leader-box">
<div class="team-leader wow fadeInDown delay-06s">
<div class="team-leader-shadow"></div>
<img src="img/team-leader-pic2.jpg" alt="">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div class="wrapper wow fadeInDown delay-05s">
<div class="counter col_fourth">
<i class="fa fa-check fa-2x"></i>
<h2 class="timer count-title" id="count-number" data-to="30" data-speed="1500"></h2>
<p class="count-text ">points</p>
</div>
</div>
</div>
<div class="team-leader-box">
<div class="team-leader wow fadeInDown delay-09s">
<div class="team-leader-shadow"></div>
<img src="img/team-leader-pic3.jpg" alt="">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div class="wrapper wow fadeInDown delay-05s">
<div class="counter col_fourth">
<i class="fa fa-check fa-2x"></i>
<h2 class="timer count-title" id="count-number" data-to="10" data-speed="1500"></h2>
<p class="count-text ">points</p>
</div>
</div>
</div>
</div>
</div>
<div class="popup" id="popup">
<div class="popup__inner">
<header class="popup__header">
<a onclick="$('#popup').fadeOut()" id="popup-exit">esc</a>
</header>
<img src="http://www.fillmurray.com/124/124" alt="Bart Veneman" width="200" height="200" class="profile__image" /><!--
--><section class="profile__details">
<ul class="profile__stats">
<li>
<h3 class="profile_stat__heading">Gold</h3>
<div class="profile_stat__number">17</div>
</li><!--
--><li>
<h3 class="profile_stat__heading">Silver</h3>
<div class="profile_stat__number">8</div>
</li><!--
--><li>
<h3 class="profile_stat__heading">Bronze</h3>
<div class="profile_stat__number">21</div>
</li>
</ul>
<h2 class="profile__name" id="popup-name"></h2>
<h2 class="profile__name">Designation: </h2>
<h2 class="profile__name">Reporting Manager: </h2>
<h2 class="profile__name">Email: </h2>
<h2 class="profile__name">Date of Join: </h2>
<h2 class="profile__name" id="popup-score"></h2>
<h2 class="profile__name">Latest Week Points: </h2>
<h2 class="profile__name">Overall Points: </h2>
<h2 class="profile__name">Medals Rewarded:</h2>
<ul class="social">
<li><i class="fa fa-github"></i></li><!--
--><li><i class="fa fa-instagram"></i></li><!--
--><li><i class="fa fa-twitter"></i></li><!--
--><li><i class="fa fa-bitbucket"></i></li><!--
--><li class="location"><i class="fa fa-map-marker"></i><span>Bangalore, IN</span></li>
</ul>
</section>
</div>
</div>
</section>
problem 2:
I am trying to make a pop-up such that when the user clicks at the points box,where the number box is,the popup is displayed.Right now it appears at the bottom of the points box.
javascript for the popup .The html is in the above codes :
< script type = "text/javascript" >
$(document).ready(function() {
$('.tab a').on('click', function(e) {
e.preventDefault();
var _this = $(this);
var block = _this.attr('href');
$(".tab").removeClass("active");
_this.parent().addClass("active");
$(".counter col_fourth").hide();
$(block).fadeIn();
});
/**
* Fade in the Popup
*/
$('.counter col_fourth').on('click', function() {
$('#popup').fadeIn();
});
}); < /script>
please help me if anyone out here can.

Categories

Resources