I have N number of html elements. Is it possible to hide the N - 10 bottom elements with jQuery and then create a "Load more" button to show another 10 elements?
I mean that when the page loads, only the 10 first elements should be visible, and when I click "Load more", the 20 first elements is visible, and when I click again, the 30 first elements is visible, etc.
Would it be something like
$('li').slice(-($('li').length - 10)).hide();
and then
var num_visible = 10;
$('#loadMore').click(function () {
$('li').slice(num_visible, num_visible + 10).show();
num_visible += 10;
});
You might need to add some further validation – this just shows the general idea – for your specific use case, but would something like this work?
var currShowing = 10;
changeShowing()
function changeShowing() {
$('div').each(function(index, value) {
if (index < currShowing - 1 ) {
$(this).show();
} else {
$(this).hide();
}
})
}
function showMore() {
currShowing += 10;
changeShowing();
}
http://codepen.io/mwvanmeurs/pen/VPoORq
Related
I have several div elements with incremental IDs (e.g. div0, div1, div2 (I know this is bad practice - I'm developing a dynamic CSV-to-HTML converter for Outlook calendar exports)) and I'd like to switch between them using jQuery linked to forward/back buttons . What I'm trying to do is as follows (in meaningless pseudo-code):
int pos = 0
forward.onclick
hide ("#div"+pos)
pos++
show ("#div"+pos)
back.onclick
if pos != 0
hide ("#div"+pos)
pos--
show ("#div"+pos)
Since I know next to nothing about jQuery, my questions are 1. What would the syntax be for implementing the above example (assuming I'm on the right track), and 2. Is there a way in jQuery to somehow check for an upper boundary so the counter doesn't increase above the number of divs?
If you want to know how many divs you have in jQuery, select them and take the length of your selection:
$('.div').length
You could even just use that selection to cycle through which divs to show:
var $divs = $('.div');
var upperLimit = $divs.length - 1;
var index = 0;
// on arrow click
$($divs[index]).hide();
index++ (or index--, depending on the arrow)
$($divs[index]).show();
int is not a data type in JavaScript. Use var. Declaration would be var pos = Number(0). To prevent exceeding the boundaries of number of divs, declare a variable with the number of divs you have, and inside your hide and show calls, use pos℅divLength instead of pos. Suppose you have total divs as 4, you will never exceed div3 this way. It will iterate from div0 to div3. Refer this to learn how to use show and hide methods.
Here's a demo.
var index = 0;
$('#div' + index).show();
$('#next').click(function () {
index++;
$('#back').prop('disabled', false);
if (index === fakeData.length - 1) {
$('#next').prop('disabled', true);
}
$('.items').hide();
$('#div' + index).show();
});
$('#back').click(function () {
index--;
$('#next').prop('disabled', false);
if (index === 0) {
$('#back').prop('disabled', true);
}
$('.items').hide();
$('#div' + index).show();
});
The above code will disable and enable the next and back buttons based on whether you are at the beginning or the end of your list of data. It hides all elements and then shows the specific one that should be shown.
I have 3 columns which include dynamically generated list elements (li tags)
these have an attribute that I try to use to hide a row / li when an amount of character is not reached in this element.(by using opacity property)
I have it working...sometimes and sometimes it only works for one column out of the 3...
So I'd appreciate some insight on what's wrong here.
(function() {
// selecting all elements with class
// class="checkout-tariff-meta-maybe-hidden"
var elems = $(".checkout-tariff-meta-maybe-hidden");
// interact between founded elements
for (var k = 0; k < elems.length; k++) {
// getting text content size
var textSize = elems[k].textContent.length;
// if text size is one we will hide element
if (textSize <= 1) {
// hiding
elems[k].style.opacity = "0";
}
}
}());
You can just go straight to the point and do something like:
// Adjust as needed
$(document ).ready(function() {
$('.checkout-tariff-meta-maybe-hidden').filter( function() {
return $(this).text().length<3; } ).hide();
});
Since you're using jQuery, to hide an element you can just do:
$(elems[k]).hide();
Alternatively, if you're looking to hide it without collapsing (since you're changing opacity, I assume this is the case), look into .fadeTo():
$(elems[k]).fadeTo(1, 0);
You might look at ...
if (textSize <= 1) {
elems[k].style.opacity = "0";
} else {
elems[k].style.opacity = "1";
}
... to ensure they get turned back on when longer.
I have a lot of click handler functions which are almost (textually and functionally) identical. I've got a menu with maybe 10 items in it; when I click on an item, the click handler simply makes one div visible, and the other 9 div's hidden. Maintaining this is difficult, and I just know there's got to be a smart and/or incomprehensible way to reduce code bloat here. Any ideas how? jQuery is Ok. The code at the moment is:
// repeat this function 10 times, once for each menu item
$(function() {
$('#menuItem0').click(function(e) {
// set 9 divs hidden, 1 visble
setItem1DivVisible(false);
// ...repeat for 2 through 9, and then
setItem0DivVisible(true);
});
});
// repeat this function 10 times, once for each div
function setItem0DivVisible(on) {
var ele = document.getElementById("Item0Div");
ele.style.display = on? "block" : "none";
}
Create 10 div with a class for marking
<div id="id1" class="Testing">....</div>
<div id="id2" class="Testing">....</div>
<div id="id3" class="Testing">....</div>
and apply the code
$('.Testing').each(function() {
$(this).click(function() {
$('.Testing').css('display', 'none');
$(this).css('display', 'block');
}
}
$(document).ready(function (){
$("div").click(function(){
// I am using background-color here, because if I use display:none; I won't
// be able to show the effect; they will all disappear
$(this).css("background-color","red");
$(this).siblings().css("background-color", "none");
});
});
Use .siblings() and it makes everything easy. Use it for your menu items with appropriate IDs. This works without any for loops or extra classes/markup in your code. And will work even if you add more divs.
Demo
Fiddle - http://jsfiddle.net/9XSJW/1/
It's hard to know without an example of the html. Assuming that there is no way to traverse from the menuItem to ItemDiv - you could use .index and .eq to match up the elements based on the order they match with the selector.
var $menuItems = $("#menuItem0, #menuItem1, #menuItem2, ...");
var $divs = $("#Item0Div, #Item1Div, #Item2Div, ...");
$menuItems.click(function(){
var idx = $(this).index();
// hide all the divs
$divs.hide()
// show the one matching the index
.eq(idx).show();
})
Try
function addClick(i) {
$('#menuItem'+i).click(function(e) {
// set nine divs hidden, 1 visble
for( var j = 0; j < 10; ++j ) {
var ele = document.getElementById("Item"+j+"Div");
ele.style.display = (i == j ? "block" : "none");
}
});
}
// One click function for all menuItem/n/ elements
$('[id^="menuItem"]').on('click', function() {
var id = this.id; // Get the ID of the clicked element
$('[id^="Item"][id$="Div"]').hide(); // Hide all Item/n/Div elements
$('#Item' + id + 'Div').show(); // Show Item/n/Div related to clicked element
});
Obviously this would be much more logical if you were using classes instead:
<elem class="menuItem" data-rel="ItemDiv-1">...</elem>
...
<elem class="ItemDiv" id="ItemDiv-1">...</elem>
$('.menuItem').on('click', function() {
var rel = $(this).data('rel'); // Get related ItemDiv ID
$('.ItemDiv').hide(); // Hide all ItemDiv elements
$('#' + rel).show(); // Show ItemDiv related to clicked element
});
Save the relevant Id's in an array - ["Item0Div", "Item1Div", ...]
Create a generic setItemDivVisible method:
function setItemDivVisible(visible, id) {
var ele = document.getElementById(id);
ele.style.display = visible ? "block" : "none";
}
And set your click handler method to be:
function(e) {
var arrayLength = myStringArray.length;
for (var i = 0; i < idsArray.length; i++) {
setItemDivVisible(idsArray[i] === this.id, idsArray[i]);
}
}
I think this will do the trick
I am a bit of a javascript noob. I want to make different content appear on my page changing once a user has clicked 3 links on the page.
So I assume I want a variable which increases on every click of the link and an if statement that makes the content appear only once the variable reaches my desired number. This is what I've got so far:
<script>
var pass = 0;
function clicked() {
pass = pass + 1;
}
</script>
Then on the links:
LINK
Then on the content
<script>
if (pass > 1) {
document.write('First<br>') }
else {document.write('Second<br>') }
</script>
It isn't working and the variable always equals 0. Any ideas?
You 'content script' is only called once (when pass is still zero).
You need to check it every time when the link is clicked:
var pass = 0;
function clicked() {
pass = pass + 1;
if (pass > 1) {
document.write('First<br>');
} else {
document.write('Second<br>');
}
}
Here is an example:
var count = 1,
topics = ['Hello', 'Well...', 'Goodbye'];
function clickHandler() {
if (count >= 3) {
changeText(Math.round((Math.random() * 2)));
count = 1;
} else {
count += 1;
}
}
function changeText(idx) {
document.getElementById('content').innerHTML = topics[idx];
}
When the link is pressed 3 times you'll get random content from the list (topics).
What is changed
In the clickHandler the counter is being reset so each 3 clicks random content will be shown
I use innerHTML instead of document.write - its better practice
count is checked on each click instead of once like you check pass.
Example here.
I've got a page with bunch of drop downs and each drop down has a button next to it. When the page initially loads I want all the buttons to be disabled and if there is a change to a specific drop down then its corresponding button shall be enabled.
I've got the following code down for this but I need to know how to loop through all the drop downs and buttons so I can generalize it.
$(document).ready(function () {
//disable all buttons
function disableAllButtons () {
$(':input[type=button]').attr("disabled", "true");
}
disableAllButtons();
//enable button when drop down changes
$(':input[name=sNewPKvalue1]').focus(function() {
disableAllButtons();
$(':input[name=Update0]').removeAttr("disabled");
})
//enable button when drop down changes
$(':input[name=sNewPKvalue2]').focus(function() {
disableAllButtons();
$(':input[name=Update1]').removeAttr("disabled");
})
////.....question?
});
Question
If I have 12 dropdowns and 12 buttons
How do I loop through all the drop downs with name sNewPKvalue[1-12] and all the buttons with name Update[0-11]
I would not recommend a loop. Just use a selector that selects the elements you want and perform the appropriate action. My first thought is to assign a CSS class to the buttons and drop down lists you are talking about. Then you can simply do something like this:
$('.dropDown').focus(function(){
$(".ddlButton").attr("disabled", "true");
$(this).closest('.ddlButton').removeAttr("disabled");
});
I would do something like:
$.each([1, 12], function(index, value) {
var valmin = val - 1;
$(':input[name=sNewPKvalue'+value+']').focus(function() {
disableAllButtons();
$(':input[name=Update'+valmin+']').removeAttr("disabled");
})
});
I didn't test this one, but you should get the idea ;)
You can do it that way.
for (var i = 0; i < 12; i++)
{
$(':input[name=sNewPKvalue'+(i+1)+']').focus(function() {
disableAllButtons();
$(':input[name=Update'+i+']').removeAttr("disabled");
})
}
Or
$(':input[name^=sNewPKvalue]').focus(function() {
disableAllButtons();
$(':input[name=Update'+(Number(this.name.match(/[0-9]+/))-1)+']').removeAttr("disabled");
})
What you could do is to make a for loop.
for(var i = 1; i <= 12; i++) {
$("select[name='sNewPKvalue"+i+"']").doSomething();
}
for(var i = 1; i <= 11; i++) {
$(":button[name='Update"+i+"']").doSomething();
}