Display & Hide Divs Sequentially on click - javascript

Basics:
I have a webpage which loads several content divs to a page, then shows them sequentially when the user clicks on the "load more" link.
Example here: JSFiddle Example
$("#load-more").click(function(e) {
var t = $(this);
if (t.data('disabled')){
return;
}
var hiddenGroups = $('.group:not(:visible)');
if (hiddenGroups.length > 0){
hiddenGroups.first().show();
} else{
t.data('disabled', true);
}
});
I have two questions based on this example:
1) The "load more" link should hide its self when the final div is showing, but is not functioning correctly in my example.
however, I'd really like it to:
2) Hide the "load more" div, and instead show/change the functionality to "Hide Items" and hide the content divs in reverse order upon click.

This is how I would do it:
JSFIDDLE
The idea:
Set a variable instructing if you are toggling more or less
var load = 'more';
check if we are loading more or less
and a function to switch the direction and the button text, to stop copy/pasting the same javascript.
Although there are only two things happening in the function, i'm working on the assumption this might grow as your application grows - if this was not to grow then it may be worth getting rid of the function andjust adding the code with the rest
The full snippet:
var load = 'more';
$("#load-more").on('click',function (e) {
// show the next hidden div.group, then disable load more once all divs have been displayed
// if we are loading more
if (load == 'more') {
// get the amount of hidden groups
var groups = $('.group:not(:visible)');
// if there are some available
if (groups.length > 0) {
// show the first
groups.first().show();
// if that was the last group then set to load less
if (groups.length == 1) {
switchLoadTo('less');
}
}
// we are loading less
} else {
// get the groups which are currently visible
var groups = $('.group:visible');
// if there is more than 1 (as we dont want to hide the initial group)
if (groups.length > 1) {
// hide the last avaiable
groups.last().hide();
// if that was the only group available, set to load more
if (groups.length == 2) {
switchLoadTo('more');
}
}
}
});
function switchLoadTo(dir) {
load = dir;
$("#load-more").html('Load ' + dir);
}

http://jsfiddle.net/8Re3t/20/
See snippet below. Probably not the most optimized code, but you get the idea and can optimize it on implementation.
var load = true;
$("#load-more").click(function(e) {
// show the next hidden div.group, then disable load more once all divs have been displayed
var t = $(this);
if (t.data('disabled')){
return;
}
var hiddenGroups = $('.group:not(:visible)');
if(load) {
hiddenGroups.first().show();
} else {
$('.group:visible').last().hide();
}
if (hiddenGroups.length > 1){
jQuery("#load-more").html("Load");
load = true;
} else {
jQuery("#load-more").html("Hide");
load = false;
}
});

Related

prevent images being loaded until click

I currently have a list of images and text, we have about 1000 images so the page load is slow.
I have a hide and show function that only loads the next three when clicked using js slice method.
My images are loaded from wp php loop, I cant use Ajax due to server limitations, is there a simple way to not load the images until the user clicks the button ?
Question
My question is how do I prevent all images from being loaded until the users clicks the button to show the next 3 images
I have tried
$(".secondary-card").each(function() {
var obj = $(this);
obj.data("objsrc", obj.attr("data-src"));
obj.hide().attr("data-src", "").before("<span class=\"loading\">loading . . .</span>");
});
but my page dose not seem much faster
Here is my current code to load the next 3 images
const cards = $('.card-deck')
let clicks = 3;
if (cards.length > 3) {
cards.hide();
cards.slice(0, 3).show();
}
$('.show-more').on('click', function() {
clicks = clicks + 3;
if (clicks > cards.length) {
clicks = cards.length
}
cards.slice(0, clicks).fadeIn();
});
Here is the approach you can proceed with:
$(.cards-desk).hide();
$('.show-more').on('click', function() {
$(.cards-desk).append("You images html code");
$(".cards-desk").show()
});

How to dynamically change tab title when it is not selected?

I want to display dynamic information (score) in the window tab of a javascript games running in a browser (chrome) : my goal is to run several instances of the game in different tabs, running in parallel, and to be able to see the current scores in the tab titles. I tried :
document.title = score
... but it works only in the selected tab, the other one are not refreshed until selected (although the games are running well in background).
==> is there a way to force the update of the tab titles... even if not selected ?
I found couple of same questions on the http://stackoverflow.com but they did not work for me.
You can find your solution here: http://www.raymondcamden.com/2010/10/19/Using-JavaScript-to-update-the-browser-window-title-when-the-user-is-away
So, basically that kind of code will work:
var focused = true;
var baseTitle = "";
var chatsMissed = 0;
//I'm the fake function that represents some process. We randomly determine if a new chat happened
function fakeStuff() {
if(Math.random() > 0.5) {
if(!focused) {
chatsMissed++;
window.document.title = baseTitle + " ("+chatsMissed+")";
}
}
}
$(document).ready(function() {
//store the base title
baseTitle = window.document.title;
//When the window is focused...
$(window).focus(function() {
focused = true;
// window.document.title = baseTitle;
//chrome bug: http://heyman.info/2010/oct/7/google-chrome-bug-when-setting-document-title/
setTimeout(function() {
document.title = baseTitle;
}, 100);
chatsMissed = 0;
});
//When the window is blurred...
$(window).blur(function() {
focused = false;
});
//setup a process
window.setInterval('fakeStuff()',2000);
})
Unfortunately JSfiddle do not support title changing. But I tested, and it works.

Javascript Logic In a loop/if statement

I have this function (transComplete) which performs the task of highlighting a relevant indicator showing the user which page they are on, each element of these controllers/indicators represents a page and will highlight appropriately.
This works independently however when I introduce a click function that allows to interact with indicators to move between pages it navigates correctly but does not highlight as needed (works only every two clicks) which leads me to believe its a logic issue in my code.
The boolean logic of true/false is the cause, the highlighting only occurs on the 'true' cases of the variable "isOnSecond" so I essentially need a solution that always highlights the relevant controller when clicked
The main function is below:
function transComplete() {
slideTransStep = 0;
crtSlideIndex = nextSlideIndex;
// for IE filters, removing filters re-enables cleartype
if (nextSlide.style.removeAttribute) {
nextSlide.style.removeAttribute("filter");
// show next slide
showSlide((crtSlideIndex >= totalSlides) ? 1 : crtSlideIndex + 1);
//Highlights a nav circle every two transitions as the boolean alternates
if (isOnSecond == true) {
//unhighlight all controls
for (var i = 0; i < slidesControllersCollection.length; i++) {
if (slidesControllersCollection[i].className === slideHighlightClass) {
slidesControllersCollection[i].className = "";
}
// highlight the control for the next slide
document.getElementById("slide-control-" + crtSlideIndex).className = slideHighlightClass;
}
isOnSecond = false;
}
else {
isOnSecond = true;
}
}
The onclick Function:
function clickSlide(control) {
showSlide(Number(control.id.substr(control.id.lastIndexOf("-")+1)),true);
}
I think you made your trans function when you were still iterating from one page to the very next, now that user can go any frame, you need to clear any highlight each time, then put it again on current one.
Or rather, for performance's sake, store the last highlighted, then highlight the new one.
But ... why not just drop the 'onSecond' logic ? It doesn't make much sense for the user to get a highlight one time over two only...
Anyway if you keep it the onSecond idea, logic would be :
if (lastHighlighted) lastHighlighted.className = "";
if (isOnSecond) {
lastHighLighted = document.getElementById("slide-control-" + crtSlideIndex);
lastHighLighted.className = slideHighlightClass;
} else {
lastHighLighted = null;
}
isOnSecond = ! isOnSecond;
But in fact i wonder if what you want is not the version without onSecond logic :
if (lastHighlighted) lastHighlighted.className = "";
lastHighLighted = document.getElementById("slide-control-" + crtSlideIndex);
lastHighLighted.className = slideHighlightClass;
(Rq declare lastHighlighted as a var so it can be in the scope of transComplete)

Jquery mega drop down loading after page loads

There may not be a fix for this. I am using a jquery drop down menu that loads when the DOM is ready. From what I understand this means it waits until the page is fully loaded until it becomes ready to be used.
This is problematic for a menu system because people want to use the menu right away often before the entire page is loaded.
Here is my site where you can see this happening.
http://bit.ly/g1sn5t
This is my script that I am using for the menu
$(document).ready(function() {
function megaHoverOver(){
$(this).find(".sub").stop().fadeTo('fast', 1).show();
//Calculate width of all ul's
(function($) {
jQuery.fn.calcSubWidth = function() {
rowWidth = 0;
//Calculate row
$(this).find("ul").each(function() {
rowWidth += $(this).width();
});
};
})(jQuery);
if ( $(this).find(".row").length > 0 ) { //If row exists...
var biggestRow = 0;
//Calculate each row
$(this).find(".row").each(function() {
$(this).calcSubWidth();
//Find biggest row
if(rowWidth > biggestRow) {
biggestRow = rowWidth;
}
});
//Set width
$(this).find(".sub").css({'width' :biggestRow});
$(this).find(".row:last").css({'margin':'0'});
} else { //If row does not exist...
$(this).calcSubWidth();
//Set Width
$(this).find(".sub").css({'width' : rowWidth});
}
}
function megaHoverOut(){
$(this).find(".sub").stop().fadeTo('fast', 0, function() {
$(this).hide();
});
}
var config = {
sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
interval: 0, // number = milliseconds for onMouseOver polling interval
over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
timeout: 0, // number = milliseconds delay before onMouseOut
out: megaHoverOut // function = onMouseOut callback (REQUIRED)
};
$("ul#topnav li .sub").css({'opacity':'0'});
$("ul#topnav li").hoverIntent(config);
});
function clearText(field){
if (field.defaultValue == field.value) field.value = '';
else if (field.value == '') field.value = field.defaultValue;
}
// JavaScript Document
Is there anyway to get this to load before everything else?
You can put those scripts wherever you whant in the case of understanding exactly what you are doing.
HTML are rendered sequentially, so scripts cannot get the DOM object or js variables defined later in the document. That's why we usually use document onload event to do the init thing since all elements are loaded.
In this case, I guess you can probably put the scripts without document.ready right after the closing of ul#topnav tag.

How to prevent iframe load event?

I have an iframe and couple of tables on my aspx page. Now when the page loads these tables are hidden. The iframe is used to upload file to database. Depending on the result of the event I have to show a particular table on my main page (these tables basically have "Retry","next" buttons...depending on whether or not the file is uploaded I have to show respective button).
Now I have a JavaScript on the "onload" event of the iframe where I am hiding these tables to start with. When the control comes back after the event I show a particular table. But then the iframe loads again and the tables are hidden. Can any one help me with this problem. I don't want the iframe to load the second time.
Thanks
mmm you said you're on aspx page,
I suppose that the iframe do a postback, so for this it reload the page.
If you can't avoid the postback, you've to set a flag on the main page just before posting back, and check against that while you're loading...
...something like:
mainpage.waitTillPostBack = true
YourFunctionCausingPostBack();
..
onload=function(){
if(!mainpage.waitTillPostBack){
hideTables();
}
mainpage.waitTillPostBack = false;
}
I am not sure what your problem is, but perhaps your approach should be a little different. Try putting code into the iframe what would call functions of the parent. These functions would display the proper table:
<!-- in the main page --->
function showTable1() {}
<!-- in the iframe -->
window.onload = function () {
parent.showTable1();
}
This would put a lot of control into your iframe, away from the main page.
I don't have enough specifics from your question to determine if the iframe second load can be prevented. But I would suggest using a javascript variable to check if the iframe is being loaded a second time and in that case skip the logic for hiding the tables,
This is my code
function initUpload()
{
//alert("IFrame loads");
_divFrame = document.getElementById('divFrame');
_divUploadMessage = document.getElementById('divUploadMessage');
_divUploadProgress = document.getElementById('divUploadProgress');
_ifrFile = document.getElementById('ifrFile');
_tbRetry = document.getElementById('tbRetry');
_tbNext=document.getElementById('tblNext');
_tbRetry.style.display='none';
_tbNext.style.display='none';
var btnUpload = _ifrFile.contentWindow.document.getElementById('btnUpload');
btnUpload.onclick = function(event)
{
var myFile = _ifrFile.contentWindow.document.getElementById('myFile');
//Baisic validation
_divUploadMessage.style.display = 'none';
if (myFile.value.length == 0)
{
_divUploadMessage.innerHTML = '<span style=\"color:#ff0000\">Please select a file.</span>';
_divUploadMessage.style.display = '';
myFile.focus();
return;
}
var regExp = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.doc|.txt|.xls|.docx |.xlsx)$/;
if (!regExp.test(myFile.value)) //Somehow the expression does not work in Opera
{
_divUploadMessage.innerHTML = '<span style=\"color:#ff0000\">Invalid file type. Only supports doc, txt, xls.</span>';
_divUploadMessage.style.display = '';
myFile.focus();
return;
}
_ifrFile.contentWindow.document.getElementById('Upload').submit();
_divFrame.style.display = 'none';
}
}
function UploadComplete(message, isError)
{
alert(message);
//alert(isError);
clearUploadProgress();
if (_UploadProgressTimer)
{
clearTimeout(_UploadProgressTimer);
}
_divUploadProgress.style.display = 'none';
_divUploadMessage.style.display = 'none';
_divFrame.style.display = 'none';
_tbNext.style.display='';
if (message.length)
{
var color = (isError) ? '#008000' : '#ff0000';
_divUploadMessage.innerHTML = '<span style=\"color:' + color + '\;font-weight:bold">' + message + '</span>';
_divUploadMessage.style.display = '';
_tbNext.style.display='';
_tbRetry.style.display='none';
}
}
tblRetry and tblNext are the tables that I want to display depending on the result of the event.

Categories

Resources