I'm trying to build an auto playing slideshow from scratch, both for a site I'm working on and as a learning exercise. As such I want to learn how to do it myself and not resort to using a plugin or one of the many excellent freely available slideshows. Here's what I've got so far:
http://jsfiddle.net/mandrill/zTdxs/15/
Heres the JS:
$("#s1").css("display", "block"); // displays slide one as default on page load
$("#slideshow").click(function () {
$(".slide").each(function (index) {
var n = index + 1;
$("#s" + n).toggle("fade");
return index;
});
});
It's currently just switching between slide one and all the other slides. How do I get it to cycle through the slides in order in a continuous loop?
As with any piece of code, if you're not sure how to do it (but are looking for a learning experience) then there's no better way of learning that looking at real live code already written. Get the (un-minified) versions of a few slideshows that you find and read the code.
My favourite slideshow plugin is the cycle one - there's a light version with fairly readable code: http://malsup.github.com/jquery.cycle.lite.js
To give you a more specific answer to your particular question, you can reset the index back to the start.
I figured out how to do it. My lack of understanding of loops was my downfall. The .each() function is not required. Here's the working JS:
$("#s1").css("display","block").addClass("active");
$("#slideshow").click(function(){
var currentSlide = $(".active").attr("id");
if ($("#slideshow .slide:last").hasClass("active")) {
$(".active").toggle("fade").removeClass("active");
$("#slideshow .slide:first").toggle("fade").addClass("active");
} else {
$(".active").toggle("fade").removeClass("active");
$("#"+currentSlide).next(".slide").toggle("fade").addClass("active");
}
});
It can be seen in action here: http://jsfiddle.net/mandrill/wLTns/6/
Thanks to all for their input :) Next step: making it autoplay and adding a timer...
Related
I created a header using jquery.flip.js, found at https://github.com/nnattawat/flip. The plugin allows several ways to trigger the flip, the two relevant ones are 'click' and 'hover'. I was hoping to have the div's flip at random intervals automatically. I did find a similar question on stackoverflow that Heretic Monkey suggested using a recursive approach (Trigger mouse click and random intervals)...
var clickHand = function() {
$("[id^='hand_'].handIcon").trigger('click');
setTimeout(clickHand, (Math.random() * 3000) + 32000);
}
clickHand();
EDIT: sorry for not being clear. In the jquery code, the following method (?) handles the flip on click, however what I would like to do is have the divs flip automatically (if possible) without a hover or click to trigger. I tried using a setTimeout inside attachEvents, but it seemed to cause an issue with the styling.
attachEvents: function() {
var self = this;
if (self.setting.trigger === "click") {
self.element.on($.fn.tap ? "tap.flip" : "click.flip", $.proxy(self.clickHandler, self));
} else if (self.setting.trigger === "hover") {
self.element.on('mouseenter.flip', $.proxy(self.hoverHandler, self));
self.element.on('mouseleave.flip', $.proxy(self.unflip, self));
}
},
I am pretty new to javascript and am having a difficult time with this and any help would be appreciated.
I created a simple codepen, demonstrating the 3D flip, https://codepen.io/coeyflyer/pen/eYZGymG.
Thank you for any suggestions,
C
Im trying to make a "spinner" much like on csgoempire.com, but I'm having some issues (I'm almost totally new to JS and I'm not good at HTML). I have tried a bunch of stuff like making one div for each picture, and having a separate JS function for each, but after some thinking I realised that it wouldn't be efficient at all and it would make it hard to change stuff later. I then decided to make separate divs for each photo, but placing them all in another div which would be moved by the JS function. This would make it a lot more efficient than before, but I can't seem to get it to work, and there are (hopefully) better ways of doing it. Id really appreciate some tips on how I can make it more efficient, and a fix for my current problem :)
Here is the code in all its glory:
console.log("Connected to server.")
function spin() {
console.log("Starting Spin.");
var boxElement = document.getElementById('allBoxes');
var pos = 900;
var id = id;
setInterval(frame, 1);
function frame() {
if (pos == 100) {
clearInterval(id)
} else {
pos--;
boxElement.style.left = pos + 'px';
}
}
}
<div id="allBoxes">
<div id="box2" style="position:absolute; left:712pt; top:150pt; width:50px; height:50px;"><img src="http://www.theaa.ie/winterhub/wp-content/uploads/2015/12/AA-logo-50x50.png" /></div>
<div id="box1" style="position:absolute; left:675pt; top:150pt; width:50px; height:50px;"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAMAAAAp4XiDAAAALVBMVEXGAA4fHx////98fHz8/Pzy8vItLS1xcXFnZ2eIiIhdXV2PCxQtHR64Aw9XFRmYSViLAAAAnklEQVRIie2UyQ6DMAxEyZAd2v//3JolAuWQdKyqAok5WDn4ZRQvGYZHj0SmqTsivs71PSS7KBEwJUaX24h3sOGMBAvn2y7RAuOBjICNvbcEAKkgckDoV0wuRkGwWH5R5HRGUr/I2FWff4toun9V5G8VY1upGRh+LPnh16wYv8ia70LR/SsilaaZSN71etNIMaKQzYhDViMWESMauZE+q+cGCDwyhBUAAAAASUVORK5CYII="
/></div>
</div>
<button onclick="spin()"> Click Me! </button>
This was made by just googling around, and testing stuff, so I'm sure its insanely bad and inefficient :P (I dont even know if its possible to do what I want to do this way.. )
The issue is that the spinner won't spin anymore.. It does when I move them separately, but not when they are both inside a div, and I move said div. Is there a way to move multiple divs by only moving one of them? Can you recommend another way of doing this if you know a better way that is more.. dynamic?
The end goal is to fetch each user's image from steam and use those images in the "spinner", make an arrow that points to the middle that will output the username of the person it lands on and have the "spinner" start once a timer reaches 0, but for now I'm just trying to learn, and I figured that the best way to learn is to have a project to work on.. (may have picked a bit of a difficult project though..)
You didn't save the interval so you can stop it:
...
var pos = 900;
var id = setInterval(frame, 1);
function frame() {
...
Made a jsFiddle with the solution: https://jsfiddle.net/bfrhw7rf/1/
Consider using css to create the spinner, like here: https://projects.lukehaas.me/css-loaders/
Since you are using a very short interval you are using up the single thread that runs your javascript, with css you are not blocking the rest of your code.
I have a problem with a vertical scroll page where I'm using (intending to, that is) two nested quickscroll functions.
This is how it's supposed to look: - just remove the scrollbar in your mind. I'm just using
overflow:scroll
here to manually check on things.
Since JS isn't my forte (I have only very basic knowledge of it), I just got a piece of code that worked similarly, reverse engineered it by removing as much as I could from the HTML and CSS until I was left with the bare function, and plugged it into my own page in terms of the needed HTML and CSS as well as the code. I'm not using anything proprietary and I'm including author links, hoping that I'm on the safe side there (?)
So, the main scroll is a vertical one and inside one of the vertical sections I'm using this 'reverse engineered' horizontal quickscroll code.
The new (nested) script cancels out the main one. Any ideas how to fix this?
The main (vertical scroll) is the following:
<script>
$(document).ready(function() {
$('a.panel').click(function () {
$('a.panel').removeClass('selected');
$(this).addClass('selected');
/* I added this to hide the menu during scroll and I'm mighty proud of myself! :) */
$('.menu').addClass('hide');
$('.book_arrow').addClass('hide');
current = $(this);
$('body').scrollTo($(this).attr('href'), 2600, function(){
$('.menu').removeClass('hide');
$('.book_arrow').removeClass('hide');
});
return false;
});
});
</script>
It comes with these two linked files:
<script type="text/javascript" src="js/jquery-1.3.1.min.js"></script>
<script type="text/javascript" src="js/jquery.scrollTo.js"></script>
The conflicting code is a bit longer:
<script>
// initialize scrollable and return the programming API
var api = $("#scroll").scrollable({
items: '#tools'
// use the navigator plugin
}).navigator().data("scrollable");
// this callback does the special handling of our "intro page"
api.onBeforeSeek(function(e, i) {
// when on the first item: hide the intro
if (i) {
$("#intro").fadeOut("slow");
// dirty hack for IE7-. cannot explain
if ($.browser.msie && $.browser.version < 8) {
$("#intro").hide();
}
// otherwise show the intro
} else {
$("#intro").fadeIn(1000);
}
// toggle activity for the intro thumbnail
$("#t0").toggleClass("active", i == 0);
});
// a dedicated click event for the intro thumbnail
$("#t0").click(function() {
// seek to the beginning (the hidden first item)
$("#scroll").scrollable().begin();
});
</script>
...and it links to this file:
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js"></script>
Does it matter where in the HTML I place all these chunks? In isolation, both scripts are working.
I've read about a seemingly similar case here and I'm thinking that maybe in my case I'm also dealing with variables that are 'occupied' by one of the functions, but I'm not exactly sure what to change and where.
I'm absolutely positively looking forward to learning a major lesson from this problem! :)
Hoping that it doesn't cause the Stack to Overflow, I'll add some more (my solution) to my journey. Maybe it helps posterity to follow my learning curve...
I was able to get the nested quick scroll (as I call it) to work properly. Still a rookie in JS, I played around with that bit of script I had gotten and modified - the one that worked vertically - and stuffed the other, similar, script for the (inner) horizontal scroll into that first script! YAY! It worked. Here's how the final script looks:
<script>
$(document).ready(function() {
$('a.panel').click(function () {
$('.book_arrow').fadeOut();
## which prevents the vertical page flying past a lot of nav during scroll down ##
$('.fluid_centerbox').addClass('hide');
$('.fluid_centerbox').fadeOut();
## which makes the scroll smooth cause what's {display:none;} isn't going to be recalculated
and also lets the viewer appreciate the background images during scroll. the 'hide' is
instant and the .fadeOut is animated. Don't ask me why it worked best in this order! ##
current = $(this);
$('body').scrollTo($(this).attr('href'), 2600, function(){
$('.book_arrow').fadeIn();
$('.fluid_centerbox').fadeIn(), 40000;
});
return false;
});
$('a.panell').click(function () {
current = $(this);
$('.long_wrap').scrollTo($(this).attr('href'), 2600, function(){
});
return false;
});
## the panell is not a typo but a way to distinguish both scroll button types ##
});
</script>
And while I'm posting this, I see that in the inner quick scroll, there's an empty
function(){});
Maybe later I'll try to get rid of it, if possible.
I have an application in which the one division contains a image that need to change in every three second. But the problem is that I also need to add some animations to that changing event. I have tried few things but those are not looking very pleasing. Is there any way I can use animate() on this? My code which just changes the images is as follows:
var arrayOfImages //asssume that this array have 10 images
var i = 0;
setInterval(function(){
$('.imageBox').attr('src', arrayImg[i]);
i++;
if(i == 10) i=0;
}, 3000);
Other then this I have tried fadeIn and fadeOut too, but this is also looking very naive.
var i = 0;
setInterval(function(){
$('.imageBox').fadeOut(500, function() {
$('.imageBox').attr("src",arrayImg[++i]);
$('.imageBox').fadeIn(500);
});
if(i == 10) i=0;
}, 3000);
Please any help on this is appreciable. Thank you in advance
this is link for fiddle http://jsfiddle.net/apf5X/8/
Have you tried jQuery Cycle 2?
It's a really powerful plugin with lots of animations. Not only for images but for any html tag!
It would probably be be easier to use a library.
Here are some suggestions to get you started:
http://flexslider.woothemes.com/
http://dimsemenov.com/plugins/royal-slider/
There are many more to choose from. A good keyword to search for would be javascript image slider or jquery image slider.
I have a slightly vague question. I have the following in my code: http://jsfiddle.net/PMnmw/2/
In the jsfiddle example, it runs smoothly. The images are swapped quickly and without any hassle. When it is in my codebase though, there is a definite lag.
I'm trying to figure out why that lag is happening. The structure of the jquery is exactly the same as above. I.e. Inside the $(document).ready (...) function, I have a check to see if the user clicked on the img (based on the classname) and then I execute the same code as in the jsfiddle.
I'm at my wits end trying to figure out what to do here... Clearly I'm not doing the swap right, or I'm being very heavy handed in doing it. Prior to this, one of my colleagues was using AJAX to do the swap, but that seems to be even more heavy duty (a full fledged get request to get the other icon...).
I've modified your fiddle: http://jsfiddle.net/PMnmw/12/
Things I've optimized:
Created a variable for both img1 and img2, so that you won't have to navigate the DOM to reference those two images anymore, thusly improving performance.
Applied a click handler to the images themselves, so you don't have to search the children of the wrapper.
The basic idea was to reduce the number of jquery selections as much as possible.
Let me know if this helped speed things up.
$(document).ready(function() {
var img1 = $('#img1');
var img2 = $('#img2');
$(".toggle_img").click(function(e) {
var target = $(e.target);
if(target.is(img1)){
img1.hide();
img2.show();
}
else if (target.is(img2)) {
img2.hide();
img1.show();
}
});
});
Images that are not visible are normally not loaded by the browser before they are made visible. If there seems to be a problem, start by downloading an image optimizer like RIOT or pngCrush to optimize your images.
If it's only two arrows, you should consider joining them into a CSS sprite.
You could try not doing everything with jQuery, but it shouldn't really make that much difference.
Something like this maybe, with the hidden image loaded in JS and some traversing done outside jQuery (but that is probably not the problem, although the code seems overly long for a simple image swap?) :
$(document).ready(function() {
var img=new Image();
img.src='http://i.imgur.com/ZFSRC.png'; //hidden image url
$(".wrapper").click(function(e) {
if(e.target.className=='toggle_img') {
$('.toggle_img').toggle();
if (e.target.parentNode.childNodes[1].style.display=='none') {
console.log("hello");
} else {
console.log("goodbye");
}
}
});
});
FIDDLE