Jquery - show no. of divs hide others - javascript

Used below HTML & JS code for below requirement.
Show first 3 divs, hide rest.
Hide Load more button if less than 3 divs (as per data-show) otherwise show.
On clicking load more button show another 3 (as per data-show value). show/hide load more button based on item exists.
Show load more button still item exists. otherwise hide load more button.
var dataShow = $('.main-wrapper').attr('data-show');
var getEle = $('.main-wrapper').find('.ele');
if (getEle.length <= dataShow) {
$('.load-more').hide();
} else {
$('.load-more').show();
}
let getEleLength = $('.ele').length;
let showItems = dataShow - 1;
//$('.ele').slice(0, 3).show();
$('.ele:gt(' + showItems + ')').hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-wrapper" data-show="3">
<div class="ele">1</div>
<div class="ele">2</div>
<div class="ele">3</div>
<div class="ele">4</div>
<div class="ele">5</div>
</div>
<button class="load-more">Load more</button>

Count div using length. Based upon that show() , hide() your div.
let size = $(".ele").length;
let x = parseInt($('.main-wrapper').data('show'));
$('.ele:lt(' + x + ')').show();
$('.load-more').click(function() {
x = (x + 3 <= size) ? x + 3 : size;
$('.ele:lt(' + x + ')').show();
if (x == size) {
$('.load-more').hide();
}
});
.ele {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-wrapper" data-show="3">
<div class="ele">1</div>
<div class="ele">2</div>
<div class="ele">3</div>
<div class="ele">4</div>
<div class="ele">5</div>
</div>
<button class="load-more">Load more</button>

Related

how do i run a javascript function that can interchange text from two different divs?

so i am building a defi app. it has three divs at the top and a table below(there is a main div which is larger than the other 2). i want to make so when i click on one div it becomes the main div and all the text from the large one switches to one of the smaller box. so far i can only move text from div 1 to div 2 but cant figure out how to move text from div 2 to div 1 in the same onclick event. please help.
<div class="row stats-row border rounded">
<div class="col-8 stats1" id="stats1">
<div class="stats1-title-amount" id="stats1-title-amount">
<div class="stats1-title">
Total Volume
</div>
<div class="stats1-amount">
$20,000,000
</div>
</div>
</div>
<div class="col-4">
<div class="row stats2a border rounded" id="stats2a">
<div class="stats2a-title-amount" id="stats2a-title-amount">
<div class="stats2-title">
Total gains
</div>
<div class="stats2-amount">
15%
</div>
</div>
</div>
<div class="row stats2b border" id="stats2b">
<div class="stats2b-title-amount" id="stats2b-title-amount">
<div class="stats2-title">
Total Volume Traded
</div>
<div class="stats2-amount">
$1,500,560
</div>
</div>
</div>
</div>
</div>
document.getElementById('stats2a').addEventListener('click', function(){
changePage1();
changePage2();
});
function changePage1 () {
document.body.style.background = 'red';
document.getElementById('stats1-title-amount').innerText = document.getElementById('stats2a-title-amount').innerText;
}
function changePage2 () {
document.body.style.background = 'red';
document.getElementById('stats2a-title-amount').innerText = document.getElementById('stats1-title-amount').innerText;
}
Use this:
document.getElementById('stats2a').addEventListener('click', function(){
const page1 = getpage1text();
const page2 = getpage2text();
changePage1(page2);
changePage2(page1);
});
function getpage1text(){
return(document.getElementById('stats1-title-amount').innerText);
}
function getpage2text(){
return(document.getElementById('stats2a-title-amount').innerText);
}
function changePage1 (text) {
document.body.style.background = 'red';
document.getElementById('stats1-title-amount').innerText = text;
}
function changePage2 (text) {
document.body.style.background = 'red';
document.getElementById('stats2a-title-amount').innerText = text;
}
document.getElementById('stats2a').addEventListener('click', function(){
let tmp = document.getElementById('stats1-title-amount').innerText;
document.getElementById('stats1-title-amount').innerText = document.getElementById('stats2a-title-amount').innerText;
document.getElementById('stats2a-title-amount').innerText = tmp;
document.body.style.background = 'red';
});
The problem you had is that you set the value of stats1 to the value stats2, and after that you set stats2 to stats1. These run one after each, you cannot run them at the same time, so in the second assignment the stats2 is already overwritten by the first assignment, so you have to store one of the values in a variable temporarily.
you can just define visibiliy for each div instead of moving content :
var visible = true;
function(){
document.getElementById('div1').style.visibility = visible ? 'hidden' : 'visible'; // use short if/else to decide which value to user
document.getElementById('div2').style.visibility = visible ? 'visible' : 'hidden'; // short if/else is called ternairy
visible = !visible; // reverse the value of itself
}

How to reveal text from a button that is clicked, then hide the previous text if new button is cllicked

I am trying to make it so that when I click on a category, the text, for that category appears. Then when a new category is clicked, the previous category text is removed, and the text for the new category takes its place. Right now, no matter what button I click, all items appear.
index.html
<div class='container'>
<button class="button">Fit guide</button>
<button class="button">Care</button>
<button class="button">Materials</button>
<div class="single-entry">
<p class="fit">lkasdnf;aksdjf;askdjflkjsdhflkajsdhflaksjdhfaksjdhflkasjdhfasjdbflaksjdhflkasdjhfkajsdbas</p>
</div>
<div class="single-entry">
<p>lkasdnf;aksdjf;askdjflkjsdhflkajsdhflaksjdhfaksjdhflkasjdhfasjdbflaksjdhflkasdjhfkajsdbas</p>
</div>
<div class="single-entry">
<p>lkasdnf;aksdjf;askdjflkjsdhflkajsdhflaksjdhfaksjdhflkasjdhfasjdbflaksjdhflkasdjhfkajsdbas</p>
</div>
</div>
index.js
const displayEntryButton = document.querySelectorAll('.button');
const test = document.querySelector('.fit');
for (var j = 0; j < displayEntryButton.length; j++) {
displayEntryButton[j].addEventListener('click', function () {
const allEntries = document.querySelectorAll('.single-entry');
for (let index = 0; index < allEntries.length; index++) {
if(allEntries[index].style.display === 'none') {
allEntries[index].style.display = 'block'
} else {
allEntries[index].style.display = 'none';
}
}
})
}
I've adjusted your code a bit to get things working.
My adjustment primarily adds an id to each entry div and a matching data-value to each button.
The id and data-value are then used for comparison when a button is clicked. If there's a match, the corresponding content is displayed.
Try the snippet below. - Comments are included within the code.
const displayButtons = document.querySelectorAll('.button');
const entryDivs = document.querySelectorAll('.single-entry');
//start for loop to iterate over each button
for (j = 0; j < displayButtons.length; j++) {
//btnValue is declared to capture the data-value attribute
const btnValue = displayButtons[j].getAttribute('data-value');
displayButtons[j].addEventListener('click', function() {
//nested loop to iterate over each entry div
for (i = 0; i < entryDivs.length; i++) {
//entryId is declared to capture the div id
const entryId = entryDivs[i].id;
//if btnValue matches entryId
if (btnValue === entryId) {
//show the corresponding content
entryDivs[i].style.display = "block"
} else {
//otherwise show nothing
entryDivs[i].style.display = "none"
}
}
})
}
/*set all entries to display none by default*/
.single-entry {
display: none;
}
<div class='container'>
<!-- Here we are setting a data-value on each button -->
<!-- The data-value must match the id for each corresponding div -->
<button class="button" data-value="fit">Fit guide</button>
<button class="button" data-value="care">Care</button>
<button class="button" data-value="materials">Materials</button>
<!-- Each div below has an id to match each buttons data-value -->
<div class="single-entry" id="fit">
<p>FIT ENTRY</p>
</div>
<div class="single-entry" id="care">
<p>CARE ENTRY</p>
</div>
<div class="single-entry" id="materials">
<p>MATERIALS ENTRY</p>
</div>
</div>

How do I count divs clicked using an event listener in javascript

I'm trying the count the total number of divs clicked and exactly which ones were clicked. I'm using an event listener because the onclick is already used. Let me clarify a bit more, first, here's my code:
<div class="wrapper">
<div class="square" onclick="classList.toggle('selected')">1</div>
<div class="square" onclick="classList.toggle('selected')">2</div>
<div class="square" onclick="classList.toggle('selected')">3</div>
</div>
<div id="dis"></div>
.selected {
background: white;
}
var numClicked = document.querySelectorAll('.wrapper');
numClicked.forEach(numClicked =>
numClicked.addEventListener('click', clickedDivs)
)
function clickedDivs () {
i = 0;
numClicked.forEach(numClicked =>
i++
var x = document.getElementById("dis");
x.innerHTML = "Squares selected: " + i;
}
What I'm trying to do with my javascript is count how many divs are selected. I'm also trying to tell exactly where ones were clicked. Let's say 1 and 2 were clicked, how do I find those were clicked and total number of divs clicked using js?
What you are doing wrong here is:
You are initialising i within the onClick event fn. which will always reset the value to 0 when ever the div will be clicked.
you are not storing anywhere which div is clicked
You are adding you'r listener on wrapper instead of .square (if you are not trying to get the value of clicked wrappers instead of clicked square)
So you can modify you'r javascript like this
<style>
.square{width: 100px; height: 100px; background: grey;}
.selected {
background: white;
}
</style>
<div class="wrapper">
<div class="square" onclick="classList.toggle('selected')">1</div>
<div class="square" onclick="classList.toggle('selected')">2</div>
<div class="square" onclick="classList.toggle('selected')">3</div>
</div>
<div id="dis"></div>
<script>
var numClicked = document.querySelectorAll('.square');
numClicked.forEach(numClick => {
numClick.addEventListener('click', clickedDivs)
}
)
var itemsClicked = [] //to store which div is clicked
function clickedDivs (e) {
var value = e.target.innerHTML;
//edit
if(itemsClicked.indexOf(value) != -1) itemsClicked.splice(itemsClicked.indexOf(value), 1)
else
itemsClicked.push(value);
var x = document.getElementById("dis");
x.innerHTML = "Squares selected: " + itemsClicked.join(",");
}
</script>
edit:
added to code to remove data from the list if already exist.
Rather than attach a handler to each div, you can use 1 window event listener. Give each clickable div an id that contains "clickable" so the event listener can filter out divs you aren't tracking. When you first click a tracked div, set its id as a key within a global object and assign 1 as the value; on additional clicks, increase value by 1.
const clicks = {};
window.addEventListener("click", (e)=> {
const id = e.target.id;
if(!id.includes("clickable"))return;
clicks[id]? clicks[id] += 1 : clicks[id] = 1;
console.log(clicks);
},)
<div class="wrapper">
<div id="clickable1" class="square">1</div>
<div id="clickable2" class="square">2</div>
<div id="clickable3" class="square">3</div>
</div>
My solution, I haven't tested it yet, test it and tell me how we adjusted it.
<div class="wrapper">
<div class="square" id="d-1">1</div>
<div class="square" id="d-2">2</div>
<div class="square" id="d-3">3</div>
</div>
<div id="result"></div>
var count = [];
var wrappers = document.querySelectorAll('.wrapper');
wrappers.forEach(square => square.addEventListener('click',() => onClickwrapperSquare(square.id));
function onClickwrapperSquare(id) {
var result = document.getElementById('result');
if(count.indexOf(id) == -1){
count.push(id);
}else{
count = count.slice(count.indexOf(id)+ 1);
}
result.innerHTML = `Squares selected: ${count.length}`;
}
This can be simply achieved by jQuery.
var count;
$(".square").click(function (){
count = count+1;
$("#dis").html(count);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class=square">1</div>
<div class="square">2</div>
<div class="square">3</div>
</div>
<div id="dis"></div>

comper div A to div B height & only if A is higher add height to div b

im trying to compare 2 divs height and just in case div A is higher add height to div B ( I have a few divs that some of the height is not heeded any adjustment
and im trying to achieve it using js but any other idea is as good
`<div class="row">
<div class="well">
<div class="col-md-1 Acomp">
<button class="btn">If this on is higher Make this one equal </button >
</div>
<div class="col-md-10 Acomp">
<p>most of the time this one height if higher no need to adjust </p>
</div>
</div>
</div>`
var elements = document.querySelectorAll(".Acomp"),
heights = [];
console.log(heights);
[].forEach.call(elements,
function(each) {
heights[heights.length] = getComputedStyle(each, null).getPropertyValue("height");
});
heights.sort(function(a, b) {
return parseFloat(b) - parseFloat(a);
newFunction(a, b);
}));
function newFunction(a, b) {
if (a < b) {
[].forEach.call(elements,
function(each) {
each.style.height = heights[0];
}); }; }
`
I think you're making the problem more complex than it really is.
Here's my solution for two divs:
/* ------------THE FIRST SOLUTION: BEGIN------------ */
const elements = document.querySelectorAll(".Acomp")
if (elements[1].clientHeight < elements[0].clientHeight) {
elements[1].style.height = elements[0].clientHeight + "px"
}
/* -------------THE FIRST SOLUTION: END------------- */
// here're two additional functions - not nicely written, but show that
// you don't just add a number to height, because that's a string
document.getElementsByClassName('addHeightB')[0].addEventListener('click', function(e) {
elements[1].style.height = parseInt(elements[1].style.height, 10) + 30 + "px"
})
document.getElementsByClassName('subtractHeightB')[0].addEventListener('click', function(e) {
elements[1].style.height = parseInt(elements[1].style.height, 10) - 30 + "px"
})
// here's the reset function for the first button
document.getElementsByClassName('setHeightToA')[0].addEventListener('click', function(e) {
elements[1].style.height = elements[0].clientHeight + "px"
})
<div class="row">
<div class="well">
<div class="col-md-1 Acomp">
<button class="btn setHeightToA">If this on is higher Make this one equal </button>
</div>
<div class="col-md-10 Acomp" style="background-color: gray; color: white;">
<p>most of the time this one height if higher no need to adjust </p>
</div>
</div>
</div>
<button class="btn addHeightB">Add 30px height to B</button>
<button class="btn subtractHeightB">Subtract 30px height from B</button>
Here's the solution for n divs:
(actually two solutions)
const elements = document.querySelectorAll(".Acomp")
let heights = []
for (let element of Object.values(elements)) {
heights.push(element.clientHeight)
}
/* ------------THE SECOND SOLUTION: BEGIN----------- */
// if the first element is the highest, then all elements should have the same height
if (elements[0].clientHeight === Math.max.apply(null, heights)) {
for (let element of Object.values(elements)) {
element.style.height = elements[0].clientHeight + "px"
}
}
/* -------------THE SECOND SOLUTION: END------------ */
/* ------------THE THIRD SOLUTION: BEGIN------------ */
// make all elements as high as the highest
heights = heights.sort().reverse()
for (let element of Object.values(elements)) {
element.style.height = heights[0] + "px"
}
/* -------------THE THIRD SOLUTION: END------------- */
/* ------------THE THIRD B SOLUTION: BEGIN------------ */
// make all elements as high as the highest
const maxHeight = Math.max.apply(null, heights)
for (let element of Object.values(elements)) {
element.style.height = maxHeight + "px"
}
/* -------------THE THIRD B SOLUTION: END------------- */
<div class="row">
<div class="well">
<div class="col-md-1 Acomp">
<button class="btn setHeightToA">If this on is higher Make this one equal </button>
</div>
<div class="col-md-10 Acomp" style="background-color: gray; color: white;">
<p>most of the time this one height if higher no need to adjust </p>
</div>
</div>
</div>
<button class="btn addHeightB">Add 30px height to B</button>
<button class="btn subtractHeightB">Subtract 30px height from B</button>

Loop a next button to return showing from the begining

$(document).ready(function() {
$(".container .parts").each(function(e) {
if (e > 1)
$(this).hide();
console.log(e);
});
$("#next").click(function() {
if ($(".container .parts:visible:last").next().length != 0) {
$(".container .parts:visible:last").next().show();
$(".container .parts:visible:last").next().show();
$(".container .parts:visible:first").hide();
$(".container .parts:visible:first").hide();
} else {
$(".container .parts:visible:last").hide();
$(".container .parts:visible:last").hide();
$(".container .parts:visible:first").next().show();
$(".container .parts:visible:first").next().show();
}
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="parts">A</div>
<div class="parts">B</div>
<div class="parts">C</div>
<div class="parts">D</div>
<div class="parts">E</div>
</div>
<div>
<button id="next">Next</button>
</div>
Hello, In the code here, I'm trying to make the script return to showing first two divs again if it is the end of the divs, But at the last one it disappears.
Ok,
I think this should do what your after, it does the (AB), (CD), (E), and then back to (AB)....
$(document).ready(function() {
var step = 0;
var dcount = 2; //how many divs shall we show..
var parts = $('.container .parts');
function showbits() {
//loop all parts
parts.each(function (x) {
//is our step in range..?
$(this).toggle(x >= step && x < step + dcount);
});
//increae our step by out div count..
step = step + dcount;
//if step is greater than length go back to 0..
if (step >= parts.length) step = 0;
}
showbits();
$("#next").click(showbits);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="parts">A</div>
<div class="parts">B</div>
<div class="parts">C</div>
<div class="parts">D</div>
<div class="parts">E</div>
</div>
<div>
<button id="next">Next</button>
</div>
$(document).ready(function() {
var $arr = $(".container .parts"), // the whole collection
index = 0; // index at which to start showing
function showNext() {
$arr.hide(); // hide all
$arr.eq(index).show(); // show the element at index (these two lines could be replaced with a for loop if the number of divs to show is dynamic: (for(var i = 0; i < numberOfDivsToShow; i++) $arr.eq(index + i).show();)
$arr.eq(index + 1).show(); // show the element at index + 1 (if any, if not don't worry as jQuery takes care of that)
index = index + 2; // increment index by 2 (if the number of divs to show is dynamic then instead of adding 2, you must add the number of divs: index = index + numberOfDivsToShow;)
if(index >= $arr.length) index = 0; // if we pass $arr.length then go back to 0
}
$("#next").click(showNext); // when clicking the #next button, show the next elements
showNext(); // by default show the first two
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="parts">A</div>
<div class="parts">B</div>
<div class="parts">C</div>
<div class="parts">D</div>
<div class="parts">E</div>
</div>
<div>
<button id="next">Next</button>
</div>
because in your code, once the last visible element becomes invisible, there are no elements visible anymore, so the :visible selector can't find any elements.
Of course there are many ways to solve this problem, but I just want to make a minimum modification to your code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="container">
<div class="parts">A</div>
<div class="parts">B</div>
<div class="parts">C</div>
<div class="parts">D</div>
<div class="parts">E</div>
</div>
<div>
<button id="next">Next</button>
$(document).ready(function() {
$(".container .parts").each(function(e) {
if (e > 1)
$(this).hide();
console.log(e);
});
$("#next").click(function() {
if ($(".container .parts:visible:last").next().length != 0) {
$(".container .parts:visible:last").next().show();
$(".container .parts:visible:last").next().show();
$(".container .parts:visible:first").hide();
$(".container .parts:visible:first").hide();
} else {
$(".container .parts:visible:last").hide();
$(".container .parts:visible:last").hide();
$(".container .parts:first").show(); //only modified these two lines
$(".container .parts:first").next().show();
}
return false;
});
});

Categories