sort divs by the number, no randomize - javascript

I found this great script: jsfiddle
Over here: Showing random divs using Jquery
The problem is that on reload the divs are randomized. I need the divs to show as they are sorted in the html, like 1,2,3,4 etc. And than of course cycle back starting over from div1.

Here's a version that works between page reloads, using the cookie plugin:
JavaScript:
var divIndex = $.cookie('div_index') || -1;
var divs = $('.Image');
divIndex = (parseInt(divIndex, 10) + 1) % divs.length;
divs.eq(divIndex).show();
$.cookie('div_index', divIndex);
Example: http://jsfiddle.net/RJMhT/124/

Try using the cycle plugin:
Updated JavaScript:
$("#slideshow").cycle();
Markup:
<div id="slideshow">
<div class="Image"><img src="/image1.jpg">1</div>
<div class="Image"><img src="/image2.jpg">2</div>
<div class="Image"><img src="/image3.jpg">3</div>
<div class="Image"><img src="/image4.jpg">4</div>
<div class="Image"><img src="/image5.jpg">5</div>
<div class="Image"><img src="/image6.jpg">6</div>
<div class="Image"><img src="/image7.jpg">7</div>
</div>
Example:
http://jsfiddle.net/RJMhT/120/

If you want to do this:
when reload, show 1, then
reload, show 2, then reload, show 3.....
you may have to use some cache technique such as localStorage to store the index of the last div, then when reload, read the last index from localStorage, calculate the next index, show it.

Edit: I think I misunderstood your question. You want a different image to load each time you actually reload the page? Seems like an odd request. Let me think about it.
Answer http://jsfiddle.net/morrison/RJMhT/133/
Features:
Uses kittens for images. (My favorite feature).
Uses the jQuery cookie plug-in when localStorage fails.
Properly cycles through a dynamic amount of images.
Answer: http://jsfiddle.net/morrison/RJMhT/123/
Features:
Uses kittens for images. (My favorite feature).
Uses the jQuery cycle plug-in.
When it hits the last one, it goes back to the first. This is default for cycle.

Related

How to get the div behind the div i clicked

Please take a look here at what I'm trying to achieve: http://jsfiddle.net/3m6r7ud2/4/
I have the following html page that looks like this:
<div class="page_conatiner" id="page1">
<img src=$file1>
<div class="page_conatiner" id="page2">
<img src=$file2>
<div class="page_conatiner" id="page3">
<img src=$file3>
And so on.
I also have a fixed button that shows up on hover:
<div class="rotate_button" id="rotate_left" ></div>
<div class="rotate_button" id="rotate_right" ></div>
This is the jQuery I'm using:
$(document).on("click", ".rotate_button", function(){
var direction = $(this).attr("id");
var page_num = ?
rotate_file(page_num,direction)
})
The buttons are in fixed locations on the page, and show on hover. When clicking on this button, I want to get which div was behind that div while clicking
so I could know which of the pages I need to rotate.
How can I do this?
First, I'm not certain what animation you are going for, but there might be a jQuery widget that will do what you want out of the box. Idk. The bootstrap one is handy, but maybe all of bootstrap is more than you want: http://getbootstrap.com/javascript/#carousel.
To answer your question: I would set a variable somewhere that keeps track of the current page num. Set it to 0 (or 1 if that's the first page number) when the page loads, and then in your click handler, increment it by 1. And then make sure to reset it to 0 (or 1) again when it gets high enough to start over. Does that answer your question?

Loop through an array of Perch CMS taglines

this is a rather complicated request.
So there are three elements to my problem. A JQuery bxslider, a Perch CMS set of taglines that my client must be able to update after website release and a javascript code block.
What I want to be able to do is create a function that replaces the <h2> element with the appropriate tagline (i.e. second product equals item 2 in perch) when the jQuery bxslider changes the image behind it.
So here's the HTML in question
<div class="overlay">
<div class="tagbox">
<h2>We provide business and personal insurance to suit your individual needs</h2>
<a class="read-more">Read more</a>
</div>
</div>
And the standard script for the bxSlider
$('.bxslider').bxSlider({
pager: true,
auto: true,
useCSS: false
// onSlideAfter: /*NEED CHANGING FUNCTION HERE*/
});
And I need a jQuery script that will use the array of taglines which I get using:
<?php perch_content('Taglines');?>
I've tried to do something like this for my function:
$(".tagbox h2").html(/*NEED TO GET ARRAY INDEX HERE i.e. heading 2, 3, 4*/);
I've tried using the $each() function to loop through that comes with jQuery but with no success. Can anyone suggest anything? Really tricky concept and I could do it if my client weren't so dependent on updating content with Perch.
I've had a similar issue with another slider, see this question: In JSSOR, how to access the current caption via Javascript?
In the same Perch template where editors enter the carousel images, you can number content (e.g. by ID) with perch_item_zero_index (starts at 0) or perch_item_index (starts at 1):
<li>
<img src="/images/730_200/tree_root.jpg" />
<div id="caption-slide-<perch:content id="perch_item_zero_index" type="hidden" />"><perch:content type="text" id="caption" label="Text for the tagline" required="true" /></div>
</li>
So the editors will enter these taglines in the same item as the slide image in perch.
As you write, bxslider has a callback for the end of each transition, so that's good. Note that the slider is initialised by assigning it to var slider, so you can access that later:
var slider = $('.bxslider').bxSlider({
onSlideAfter: function(){
// get the text and place it somewhere else
}
});
Now all you need is to know which slide you're in. See http://bxslider.com/options
If you know that, you can fetch your content at the end of each transition and place it somewhere else in the DOM:
var slider = $('.bxslider').bxSlider({
onSlideAfter: function(){
// which slide are we in?
var current = slider.getCurrentSlide();
// get the text from the caption that corresponds to the current slide
// and place it somewhere else in the dom
$(".tagline h2").text($("#caption-slide-" + current).text());
}
});
Untested, but basically, that should be it. Note that there is an issue on https://github.com/stevenwanderski/bxslider-4/issues/604 saying that it might not work yet with "auto".

jquery fadeOut not working - update

i mean i wanna iterate manually using a for-loop or something. but this piece of code i came up with seems to be not working. i like combining javascript with jquery since jquery is not my cup of tea for major projects. i don't know much jquery either, i would say I'm beginning to learn, though. how do you iterate over a nodelist in jquery is the question i have for all those jquery fans this time. is it similar to the javascript way? anyway this is what i have come up with (the code of a beginner).
HERE'S THE CODE //not working
$(".sn").[0].fadeOut();
$(".sn").[0].fadeOut("slow");
$(".sn").[0].fadeOut(3000);
<div class="sn">
content
</div>
<div class="sn sn-2">
content
</div>
<div class="sn sn-3">
content
</div>
but $(".sn-2").fadeOut(); works like charm. why?
$('.sn').each(function(){
$(this).fadeOut('slow');
});
in your code, you're trying to fadeout the .sn div three times.
try the following:
$.each($('.sn'), function(i, obj) {
$('.sn:eq(' + i + ')').fadeOut(3000);
});
this way you'll be iterating over all the .sn class elements, and fade them out one by one by its index (:eq(i))
try this
$(".sn:first").fadeOut();
you can try this also :
for(var i=0; i < $(".sn").length; i+=1){
$(".sn").eq(i).fadeOut(3000);
}
Maybe you are looking for something like this?
It will fade out each sn element within a loop.
I also updated the html to make it more consistent
for(var i=0; i < $(".sn").length; i+=1){
$(".sn-"+[i]).fadeOut(3000);
}
HTML
<div class="sn sn-0"> content </div>
<div class="sn sn-1"> content </div>
<div class="sn sn-2"> content </div>
Further you need to know, that $(".sn") represents an object, which does not have any property [0] which you are trying to access with your code ($(".sn").[0])
So to make this work you have to access the element you want to trigger by any event like this $(".sn")[0].
Best

JS - Shouldn't this be written better? One function vs multiples?

I have a tweet stream where new tweets are added at the top and the older ones pushed down. You can click on the entire tweet and a panel slides down to reveal, "reply", "retweet", "favorite" etc. The panel is added to each new tweet added in the stream.
The code below works. Shouldn't this be better written so that only one call is being made? Or, as a new tweet is added. would I just have to add to the code with div#tc4, ul#tb4 etc?
$(document).ready(function () {
$("div#tc1").click(function () {
$("ul#tb1").slideToggle("fast");
});
$("div#tc2").click(function () {
$('ul#tb2').slideToggle("fast");
});
$("div#tc3").click(function () {
$('ul#tb3').slideToggle("fast");
});
});
Added Markup:
<div id="tc1" class="tweetcontainer">
<div class="avatarcontainer">
<div class="avatar"></div>
</div>
<div class="content">
<div class="tweetheader">
<div class="name">
<h1>John Drake</h1>
</div>
<div class="tweethandle">
<h2>#Drakejon</h2>
</div>
<div class="tweettime">10m</div>
</div>
<div>
<p>Exceptional Buys Ranger To Give Monitoring Shot In The Arm To Its 'DevOps' Platform http://tcrn.ch/11m3BrO by #sohear </p>
</div>
</div>
</div>
<!-------------Tool Bar -------------------------------->
<ul id="tb1" class="toolbar">
<li><a class="reply" href="#"><span>reply</span></a></li>
<li><a class="retweet" href="#"><span>retweet</span></a></li>
<li><a class="favorite" href="#"><span>favorite</span></a></li>
<li><a class="track" href="#"><span>track</span></a></li>
<li><a class="details" href="#"><span>details</span></a></li>
</ul>
I highly recommend separating your javascript from your detailed page function. The best way to do this is to put the retweeting panel inside the tweet container, then you don't even need to give it an id at all or encode in the javascript information about your html structure and ids. You can then just do:
$('.tweetcontainer').on('click', function(event) {
if ($(event.target).is(':descendantof(.toolbar)')) {
//ignore all clicks within the toolbar itself
return;
}
$(this).find('.toolbar').slideToggle();
});​
It's that easy! See it in action in a jsFiddle.
Now you can add as many tweet containers as you want to your page--and your javascript doesn't have to change one bit. Other solutions that require knowledge of specific ids linking to specific ids are suboptimal.
Note the descendantof pseudo-selector is custom (see the fiddle to find out how it works). Also, since you didn't provide any css, I had to choose some--it was quick so don't expect much. (Aww heck I just saw you updated your question to provide a jsFiddle with css giving a far prettier result--but I won't change mine now.) I did have to add a class to the actual tweet itself, but there is probably a better way to style it.
And if you want a click on the displayed toolbar itself (outside of a link) to allow collapsing the toolbar, change the code above to :descendantof(a).
If you don't want to change your page layout, another way to it is to encode the information about the linkage between html parts in the html itself using a data attribute. Change your tweetcontainer div to add a data attribute with a jQuery style selector in it that will properly locate the target:
<div class="tweetcontainer" data-target="#tb1">
You don't really have to remove the id if you use it elsewhere, but I wanted you to see that you don't need it any more. Then on document.ready:
$('.tweetcontainer').click(function () {
$($(this).data('target')).slideToggle('fast');
});
Here is another jsFiddle demonstrating this alternate technique (though it less elegant, in my opinion).
Last, I would like to mention that it seems possible you have a little bit of "div-itis". (We have all been there.) The toolbar anchor elements have unnecessary spans inside of them. The tweet name h1 element is inside a div, but could just be an h1 with class="name" instead.
In general, if there is only a single item inside a div and you can change your stylesheet to eliminate the div, then the div isn't needed. There are an awful lot of nested divs in your html, and I encourage you to remove as many of them as you can. Apply style to the other block elements you use and at least some, if not many, won't be needed.
I'd suggest (though currently untested):
$('div[id^="tc"]').click(function(){
var num = parseInt(this.id.replace(/\D+/g,''),10);
$('#tb' + num).slideToggle("fast");
});
Though given that you don't need the num to be a number (it'd be fine as a string), you could safely omit the parseInt().
Yes, you can write this code much more compactly like this:
$(document).ready(function() {
for (var i = 1; i < 3; i++) {
$("div#tc" + i).click(function() { $("ul#tb" + i).slideToggle("fast"); } );
}
});

Continuously fade a list of thumbnails on top of each other w/ Jquery (only showing 4 at all times?)

I'm not exactly sure how to tackle this one. I've checked out the jQuery "Cycle" plugin, but haven't seen any exmaples of what I really need.
How would you achieve fading in a list of thumbnails from the HTML (maybe something like:
<ul id="container">
<li class="thumbnail"> <img src="1.jpg"/> </li>
<li class="thumbnail"> <img src="2.jpg"/> </li>
<li class="thumbnail"> <img src="3.jpg"/> </li>
<li class="thumbnail"> <img src="4.jpg"/> </li>
<li class="thumbnail"> <img src="5.jpg"/> </li>
...more
</ul>
I've created a sample .GIF to explain what i'm trying to do:
-There are a total of 4 boxes showing at all times
-Jquery will pull the next image on the list, and fade it into one of the 4 boxes (random box every time). (image will fade in over the last image in the box).
-This should only happen if there are more than 4 images inside the list. (stay static if we only have 4)
-Would like to have the ability to add more images via HTML, not inside the JS...
----UPDATE------
Kalle seems to have the correct solution, the only thing missing is the ability to control how many visible thumbnails you see at all times.
I worked 5 (+ 2, ver 1.1) hours on your question. The biggest problem was the switch between two elements. It turns out, that there isn't any "swapping" function.. So I made an alternative.. You cant make this fading transition any better, but it is fairly close your GIF. If you want just to swap them nice and dirty, without any fade.. then that's very easy to make.
Anyways, I composed into a plugin:
JoeShuffle v1.1
A simple jQuery plugin to shuffle list. Very easy to install and use. Works like any other jQuery plugin. Just add jQuery to your page, include the script with necessary css file. Then, call it to some list and voila! You can change the interval-speed like this: $('#JoeShuffle').JoeShuffle({intervalSpeed: 2000});
As of Ver 1.1 also randomizes the list on the first load and enables to have this script hooked to multiple lists. Also you can set the max. number of displayed elements:
$('#JoeShuffle').JoeShuffle({displayElements: 4});.
JoeShuffle v1.1 [ Download (33.54 KB) - View demo (jsfiddle) ]
JoeShuffle v1.0 [ Download (65.12 KB) - View demo (jsfiddle) ]
NOTES
I'm not sure how crossbrowser it is and also it is very dirty and raw plugin. Surely could use some optimization, however it does work.
My examples use colorful boxes, but it really doesn't matter if there are images or whatever in the li element.
Some features:
Remembers the last slot/position, where the swap was made, and wont use it again. Otherwise it will look kinda a weird
You can set your own custom interval-speed
Shuffles whatever you put between the list tags. However, you should keep all of them in one size
(v1.1) Randomizes all the elements in the ul list on the first load.
(v1.1) Allows you to set the max. number of elements displayed at once
(v1.1) Enables you to have this script hooked to multiple lists at once
Currently it works like this. Whatever you put inside the li elements, it will shuffle them. If you have 5 elements, then it will hide one. And then basically take the hidden element and swap it with some random element. However, I will revisit it in ~15 hours and add the option, that you can set how many are being displayed. So you can actually have 10 elements in the list, but you will only display 4 at the time, there for making the randomization more dynamic.
Rev 1 notes
Since you wanted to randomize them on the first load. Then I added the rand() plugin to this script. This way it makes the first hide() loop very neat and also works as randomizer on the full list..even thought it actually doesn't randomize the list separately..meaning its faster. As I mentioned in the comments inside the scrip, rand() plugin by Alexander Wallin, is a must have in your jQuery collection.
As you can see, you can hook it to multiple lists from now on. That and also adding more elements to the list came up a new problem. That the script was loading slow and all the elements would be shown for few ms, on the first load. I fixed the problem, by adding the scripts includes inside the <head> and not after the contents of the page. This way the scripts get loaded before the elements.. and that means everything is smooth.
Though I have no idea what happens, if the displayElements option is set lower, then the actual elements count inside the list. Best avoid such situations.
Also if you noticed that the elements get floated together in CSS. You could also use display: inline-block;, but inline-block isn't very crossbrowser, so I used float. This however means, that under the elements you should have clear: both; in some form.. Or maybe even some wrapper around the list.
http://jsfiddle.net/MbQrw/
This should cover the basic stuff you're needing. It's not very elegant and stuff like initialization is missing, but the main technique is shown.
http://jsfiddle.net/rkw79/VETmf/
The concept is similar: grab an element in a list, do an action, move onto the next element, and if it is the end; loop back to the beginning.
$('input').click(function (e) {
toggleImg($('div img:first'));
});
function toggleImg(I) {
var nextI = I.next();
if (nextI.length == 0) nextI = $('div img:first');
I.toggle('slow', function() {
toggleImg(nextI);
});
}
Now this doesn't pre-populate the divs with images and it doesn't handle getting the link code in with the images as they display but you can handle that with just a little extra work.
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js" type="text/javascript"></script>
<script>
var maxDisplay = 4;
var displayBox;
$(document).ready(function() {
StartShow();
});
function StartShow() {
var interval = 5000;
var slideShowID;
slideShowID = setInterval(Gallery, interval);
}
function Gallery() {
var nextImage = $("#container li.selected").next().length;
displayBox = Math.floor(Math.random() * maxDisplay);
if (nextImage > 0){
$("#container li.selected").removeClass("selected").next().addClass("selected");
imgSrc = $("#container li.selected").children().attr("src");
if(imgSrc != null) {
$("#" + displayBox).fadeOut('slow', function() { $("#" + displayBox).css("background-image", imgSrc); }).fadeIn();
}
}
else {
$("#container li.selected").removeClass("selected").siblings(':first').addClass("selected");
imgSrc = $("#container li.selected").children().attr("src");
if (imgSrc != null) {
$("#" + displayBox).fadeOut('slow', function() { $("#" + displayBox).css("background-image", imgSrc); }).fadeIn();
}
}
}
</script>
</head>
<body>
<ul id="container" style="display: none;">
<li class="thumbnail selected"> <img src="1.jpg"/> </li>
<li class="thumbnail"> <img src="2.jpg"/> </li>
<li class="thumbnail"> <img src="3.jpg"/> </li>
<li class="thumbnail"> <img src="4.jpg"/> </li>
<li class="thumbnail"> <img src="5.jpg"/> </li>
<li class="thumbnail"> <img src="6.jpg"/> </li>
<li class="thumbnail"> <img src="7.jpg"/> </li>
<li class="thumbnail"> <img src="8.jpg"/> </li>
<li class="thumbnail"> <img src="9.jpg"/> </li>
</ul>
<div>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
</div>
</body>
</html>
So I have a jsFiddle with much more in the way of settings but i'm only posting the sinmplest part of the code here. I didn't use images just <li> elements with background colours.
var floor = Math.floor;
var random = Math.random;
function randomindex(num, style) {
return floor(random() * num);
};
$.fn.continuousFade = function(options) {
var settings = $.extend({
"max_visible": 4,
"delay": 2000, // in ms.
"speed": 500, // in ms.
"style": "normal"
}, options);
var children = this.children(".thumbnail").css("display", "");
for (var i = 0; i < settings.max_visible; i++) {
children.eq(i).css("display", "inline-block");
}
function fadeone() {
var visibleChild = this.children(".thumbnail:visible").eq(randomindex());
var hiddenChild = this.children(".thumbnail:not(:visible)").first();
var parent = this;
visibleChild.before(hiddenChild);
hiddenChild.css({
"position": "absolute",
"opacity": 0,
"display": "inline-block"
}).animate({
opacity: 1
}, settings.speed, function() {
hiddenChild.css("position", "");
parent.append(visibleChild.css("display", "")); // Need to put this one at the end so it will get displayed again last.
});
setTimeout(function() {
fadeone.call(parent);
}, settings.delay);
}
fadeone.call(this);
};
The jsFiddle has options for other ways of getting a random image and the ability to change the settings and it shows more children.
Current jsfiddle:- http://jsfiddle.net/Nft5a/42/
It's been a while, but maybe this will work for your defining # of images problem:
what I would do involves doing a bit of math, but say I want 4 pictures showing at all times, and they are 50px each with no margin or padding (margins and padding is where the math really comes into play) then I would put them in a div that is 200px wide (4*50) with overflow set to hidden in the html (where your list should be with the images). this is explained a bit more in this question: "http://web.enavu.com/tutorials/making-an-infinite-jquery-carousel/"
hope that helps.

Categories