I have several sections like this:
<section class="one">
<div class="two over" element="myelement1">
<div class="front" >
<img src="element.jpg" width ="100%;" height ="100%;" alt="">
</div>
<div class="back">
</div>
</div>
</section>
<section class="one ">
<div class="two over" element="myelement2">
<div class="front" >
<img src="element2.jpg" width ="100%;" height ="100%;" alt="">
</div>
<div class="back">
</div>
</div>
</section>
Then I have a function like:
var i = j =0;
$(function () {
$('.over').hover(function () {
/*do something*/
}, function () {
if ( $(this).attr('element') == 'myelement1'){
img = $(this).find('img');
img.attr('src', arr_1[i]);
i++;
if(i > arr_1.length-1) i=0;
}
if ( $(this).attr('element') == 'myelement2'){
img = $(this).find('img');
img.attr('src', arr_2[j]);
j++;
if(j > arr_2.length-1) j=0;
}
});
})
How can I store in global variables or maybe a dictionary
the values of each img = $(this).find('img'); so I do this only once and not every time the user is in .hover?
First off, you probably don't need to solve the problem you're trying to solve. Modern computer are so fast that searching the children of an object for imgs is a very fast operation (unless perhaps there are thousands). So, you probably shouldn't be trying to optimize this at all unless you have actual performance data that says there really is a problem here.
Always measure before optimizing to know what problems are actually there and actually need solving. Then, measure any potential solution to see if it's actually doing what you need.
As to the actual question you ask, there are a couple options.
You can retrieve it the first time and then just save it in a global:
var i = j =0;
var imgs1, imgs2;
$(function () {
$('.over').hover(function () {
/*do something*/
}, function () {
if ( $(this).attr('element') == 'myelement1'){
if (!imgs1) {
imgs1 = $(this).find('img');
}
imgs1.attr('src', arr_1[i]);
i++;
if(i > arr_1.length-1) i=0;
}
else if ( $(this).attr('element') == 'myelement2'){
if (!imgs2) {
imgs2 = $(this).find('img');
}
imgs2.attr('src', arr_2[j]);
j++;
if(j > arr_2.length-1) j=0;
}
});
})
or, more in the spirit of jQuery, use .data() instead of globals:
var i = j =0;
$(function () {
$('.over').hover(function () {
/*do something*/
}, function () {
var imgs = $(this).data("imgList");
if (imgs) {
imgs = $(this).find('img');
$(this).data("imgList", imgs);
}
if ( $(this).attr('element') == 'myelement1'){
imgs.attr('src', arr_1[i]);
i++;
if(i > arr_1.length-1) i=0;
}
else if ( $(this).attr('element') == 'myelement2'){
imgs.attr('src', arr_2[j]);
j++;
if(j > arr_2.length-1) j=0;
}
});
})
Related
I need to show three images one by one with using javascript setinterval function can you please any one help me.
Bellow is my html code.
<div class="imageHolder">
<img src="http://lorempixel.com/400/200/sports/" style="display:none;" class="image1" border="0" />
<img src="http://lorempixel.com/400/200/sports/1" style="display:none;" class="image2" border="0" />
<img src="http://lorempixel.com/400/200/" style="display:none;" class="image3" border="0" />
</div>
<head>
<script type="text/javascript">
function start() {
var images = document.querySelectorAll('.imageHolder img');
var images_count = images.length;
var image_index = false;
var delay = 3000; // 3 seconds delay
function animateImageHolder() {
if (false !== image_index) {
images[image_index].style = 'display:none';
image_index++;
image_index = (image_index < images_count ? image_index : 0);
} else {
image_index = 0;
}
images[image_index].style = 'display:inline';
}
animateImageHolder();
setInterval(animateImageHolder, delay);
}
</script>
</head>
<body onload="start()">
<!-- ... -->
This question is pretty much like "do my job for me" but you are honest in your english.
You did not say how long each image should be visible so I set it to 3 seconds (interval = 3000).
I recommend you to set the style attribute of the first image to be style="display:block" and the rest to style="display:none".
function slider(element) {
var next_image = 0
, interval = 3000
, images = Array.prototype.filter.call(element.children, function(child) {
return child.tagName === "IMG";
})
;
setInterval(function() {
images.forEach(function(image, i) {
image.style.display = i === next_image ? "block" : "none";
})
next_image = (next_image + 1) % images.length;
}, interval);
}
slider(document.querySelector("div.imageHolder"))
I made an Image-Slider based on Radio Buttons (thanks to some advice of user A.V) as you can see here:
Now, there is one last thing that I would love to do but I have no idea how. I would like to be able to switch to the next image by clicking on the image itself (of course with the selection jumping to the next button, too).
Would be awesome if someone could help. Thanks in advance!
JSFiddle
http://jsfiddle.net/v4phdL3p/8/
Add class "sliderImage" to your image placeholders and then use this code:
$(".sliderImage").click(function(){
var name = $(this).attr("name")
var selector = "input[checked][name='" + name +"']"
currrentRadio = $(selector)
currrentRadio.removeAttr("checked")
if (currrentRadio.next().attr("name") === name) {
currrentRadio.next().attr('checked', 'checked').prop("checked",true).trigger("click")
} else {
var nextRadio = "input[name='" + name + "']"
firstRadio = $(nextRadio)[0]
$(firstRadio).attr('checked', 'checked').prop("checked",true).trigger("click")
}
})
*EDIT* change changeImage to this (to allow clicking of object to not affect functionality):
Here is the working fiddle:
http://jsfiddle.net/xhmrwhtv/3/ **NEW modified Working Fiddle**
function changeImage(imgName, obj)
{
image = document.getElementById(obj.name);
image.src = imgName;
var name = obj.name;
var selector = "input[checked][name='" + name +"']";
currrentRadio = $(selector);
currrentRadio.removeAttr("checked");
$(obj).attr('checked', 'checked').prop("checked",true).trigger("click");
}
Have you tought about a simple JavaScript or jQuery script? This would not be hard to do, here is an example:
jQuery:
function slideSwitch() {
var $active = $('#slideshow IMG.active');
if ($active.length == 0) $active = $('#slideshow IMG:last');
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
$active.addClass('last-active');
$next.css({ opacity: 0.0 })
.addClass('active')
.animate({ opacity: 1.0 }, 1000, function () {
$active.removeClass('active last-active');
});
}
$(function () {
setInterval("slideSwitch()", 3000);
});
html:
<div style="width: 100%; position: absolute; margin-top:5%;">
<div id="slideshow" style="display: inline-block; position:relative;">
<img src="pictures/coinWars/1.jpg" class="active" />
<img src="pictures/coinWars/2.jpg" />
<img src="pictures/coinWars/3.jpg" />
<img src="pictures/coinWars/4.jpg" />
<img src="pictures/coinWars/5.jpg" />
<img src="pictures/coinWars/6.jpg" />
<img src="pictures/coinWars/7.jpg" />
<img src="pictures/coinWars/8.jpg" />
<img src="pictures/coinWars/9.jpg" />
<img src="pictures/coinWars/10.jpg" />
</div>
That will make a simple slide show of pictures, you can change it to allow it to change on click, instead on on the interval.
This is my code, but feel free to use it and modify it as necessary.
First change you function to access the name not the object
function changeImage(imgName, name)
{
image = document.getElementById(name);
image.src = imgName;
}
Then then add to img onclick:
<img src="http://placehold.it/100x100" name="image1" id="image1" onclick="changeImageClick(1);"><br>
Then I added variables (just for the first set of changes:
var images1 = ["http://placehold.it/100x100","http://placehold.it/200x200","http://placehold.it/300x300"];
var images1num = 0;
images1num is for what current image src you are on. Starting at 0 to 2.
Then you have to modify the radio buttons onclick to:
changeImage('http://placehold.it/200x200','image1'); images1num = 1;
Here is the function:
function changeImageClick(num)
{
if(num == 1)
{
images1num = (images1num + 1) % images1.length;
changeImage(images1[images1num],'image1');
var input = document.getElementsByTagName('input');
var nextInput = false;
for(var i = 0; i < input.length; i++)
{
if(input[i].checked == true && input[i].name == 'image1')
{
nextInput = true;
if(nextInput)
{
input[(i+1)%images1.length].click();
nextInput = false;
break;
}
}
}
}
}
Again this is only for your 100x100,200x200,300x300 but the concept works for all 3.
Here is JSFiddle: http://jsfiddle.net/v4phdL3p/44/
Replicating the other two sliders is a good learning experience.
There are many javaScript sliders. You just need to search google to get your answer. However, following code may be helpful.
Working Fiddle....
<img id = "img" src = "http://www.menucool.com/slider/prod/image-slider-1.jpg" width = 200; onclick = "changeImage()">
<br>
<input type="radio" name = "rdo" id = "radio1" onclick = "changeSlide(this)" checked />
<input type="radio" name = "rdo" id = "radio2" onclick = "changeSlide(this)"/>
<input type="radio" name = "rdo" id = "radio3" onclick = "changeSlide(this)"/>
JavaScript:
function changeImage(){
if(document.getElementById("img").src == "http://www.menucool.com/slider/prod/image-slider-1.jpg" ){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-3.jpg";
document.getElementById("radio2").checked = true;
}
else if(document.getElementById("img").src == "http://www.menucool.com/slider/prod/image-slider-3.jpg"){
document.getElementById("img").src ="http://www.userinterfaceicons.com/80x80/minimize.png";
document.getElementById("radio3").checked = true;
}
else if(document.getElementById("img").src == "http://www.userinterfaceicons.com/80x80/minimize.png"){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-1.jpg";
document.getElementById("radio1").checked = true;
}
}
function changeSlide(id){
if(document.getElementById("radio1")==id){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-1.jpg";
}
else if(document.getElementById("radio2")==id){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-3.jpg";
}
else if(document.getElementById("radio3")==id){
document.getElementById("img").src ="http://www.userinterfaceicons.com/80x80/minimize.png";
}
}
I have a list of div elements, all with float:left one after another like so
<div id="container">
<div id=0" style="float:left;> Stuff </div>
<div id=1" style="float:left;> Stuff </div>
<div id=2" style="float:left;> Stuff </div>
...
<div id=n" style="float:left;> Stuff </div>
</div>
What I am trying to achieve is the following:
If I click on one of the divs, it will push the surrounding divs away (the ones on its left up and the ones on its right down) and populate its own row. Then when clicked again it returns to the original configuration.
My Attempts:
Add a brute force separator: just use jQuery to stack before and after the div
Toggle the CSS property: clear: both for the desired div
It may be because it is rather late, but neither of these approaches seem reliable. What would be a more reasonable means of attaining this functionality?
Thanks for your time!
I think you want to achieve this, please check this Fiddle
var parentWidth = $("#container").css("width");
var originalWidth = $($("#container div")[0]).css("width");
$("#container div").click(function(){
if($(this).css("width") != parentWidth) {
$(this).css("width",parentWidth);
}
else {
$(this).css("width",originalWidth);
}
});
var divWidth = 250;
var n= 5; //this will be no of inner divs
$(function(){
$('#container div').each(function(index, element) {
$(this).click(function(e) {
if($(this).width() == divWidth)
{
var dt = divWidth;
if(index != 0)
{
$(this).prev().hide();
dt += divWidth;
}
else if(index < n)
{
$(this).next().hide();
dt += divWidth;
}
$(this).width(dt);
}
else
{
$(this).width(divWidth);
if(index != 0)
{
$(this).prev().show();
}
else if(index < n)
{
$(this).next().show();
}
}
});
});
});
I have a small problem with a small jQuery script that my slide images. The script itself works very well, its purpose being to scroll through the images indeed "fade", a classic.
The problem is that if I want to use it for another block on the page, well it no longer works properly .. The problem is certainly located at the id, but can not make it work.
Here is the script:
function slider() {
function animate_slider(){
$('.slider #'+shown).animate({
opacity:0 // fade out
},1000);
$('.slider #'+next_slide).animate({
opacity:1.0 // fade in
},1000);
//console.log(shown, next_slide);
shown = next_slide;
}
function choose_next() {
next_slide = (shown == sc)? 1:shown+1;
animate_slider();
}
$('.slider #1').css({opacity:1}); //show 1st image
var shown = 1;
var next_slide;
var sc = $('.slider img').length; // total images
var iv = setInterval(choose_next,3500);
$('.slider_nav').hover(function(){
clearInterval(iv); // stop animation
}, function() {
iv = setInterval(choose_next,3500); // resume animation
});
$('.slider_nav span').click(function(e){
var n = e.target.getAttribute('class');
//console.log(e.target.outerHTML, n);
if (n=='prev') {
next_slide = (shown == 1)? sc:shown-1;
} else if(n=='next') {
next_slide = (shown == sc)? 1:shown+1;
} else {
return;
}
animate_slider();
});
}
window.onload = slider;
Any idea ? Thank you all :)
i am not sure of what u want to do, but if you want reusibality :
EDIT : i ve modified assuming that your 2 slides are independant
this is a quick solution, as mentioned #David Barker, it would be more clean to do a jQuery plugin
JS :
var sliderTop = "#slider.top";
var sliderBottom = "#slider.bottom";
function slider(el) {
function animate_slider(el){
$(el + shown).animate({
opacity:0 // fade out
},1000);
$(el + next_slide).animate({
opacity:1.0 // fade in
},1000);
//console.log(shown, next_slide);
shown = next_slide;
}
function choose_next(el) {
next_slide = (shown == sc)? 1:shown+1;
animate_slider(e);
}
$(el + ' #1').css({opacity:1}); //show 1st image
var shown = 1;
var next_slide;
var sc = $(el + ' img').length; // total images
var iv = setInterval(choose_next,3500);
$(el + '_nav').hover(function(){
clearInterval(iv); // stop animation
}, function() {
iv = setInterval(choose_next,3500); // resume animation
});
$(el + '_nav span').click(function(e){
var n = e.target.getAttribute('class');
//console.log(e.target.outerHTML, n);
if (n=='prev') {
next_slide = (shown == 1)? sc:shown-1;
} else if(n=='next') {
next_slide = (shown == sc)? 1:shown+1;
} else {
return;
}
animate_slider(el);
});
}
window.onload = function() {
slider(sliderTop);
slider(sliderBottom);
}
HTML :
<div id="slider" class="top">
<h2>Nos partenaires</h2>
<img id="1" src="" alt="">
<img id="2" src="" alt="">
<img id="3" src="" alt="">
</div>
<div class="slider_nav">
<span class="prev">Précédent</span><!--
--><span class="next">Suivant</span>
</div>
<div id="slider" class="bottom">
<h2>Nos partenaires</h2>
<img id="1" src="" alt="">
<img id="2" src="" alt="">
<img id="3" src="" alt="">
</div>
<div class="slider_nav">
<span class="prev">Précédent</span><!--
--><span class="next">Suivant</span>
</div>
Basically, what I'm trying to do is shuffle through images using some JavaScript code. All it does is change the display style of the current image to block, and at the same time change the previous one to none.
The HTML code:
<body>
<img src="http://bit.ly/yOqqbg" id="image1" style="display: block;">
<img src="http://bit.ly/dezBUZ" id="image2" style="display: none;">
<img src="http://bit.ly/IvM5HE" id="image3" style="display: none;">
</body>
The JavaScript code:
var id = ["image1", "image2", "image3"]; //Array with the id's in the document you want
to shuffle through
var i = 0; //Set inital array element
initiateTimer(); //Get the loop going
function initiateTimer() {
if (i > id.length) {
i = 0;
initiateTimer();
}
setTimeout(function() { changeElement(); }, 2000); //2000 = 2 seconds
}
function changeElement() {
if (id === 0) {
document.getElementById(id[2]).style.display = 'none';
document.getElementById(id[i]).style.display = 'block';
} else {
document.getElementById(id[i - 1]).style.display = 'none';
document.getElementById(id[i]).style.display = 'block';
}
i += 1;
initiateTimer();
}
when i === 3 you will have problems
if (i > id.length) {
should become
if (i >= id.length) {
UPDATE: http://jsfiddle.net/HgNuc/