I am using this code
http://jsfiddle.net/sagive/cAsB3/
my question is how to pause the slider when mouse is on the pictures(hover).
$.getJSON('assets/json/slides.json', function(data) {
$("h2").html(data[0].title);
$.each(data, function (i, f) {
if(i>0){
$("#exampleSlider").append("<li><img src=" + f.content + "/></li>");
}
});
});
$(function () {
/* SET PARAMETERS */
var change_img_time = 3000;
var transition_speed =200;
var simple_slideshow = $("#exampleSlider"),
listItems = simple_slideshow.children('li'),
listLen = listItems.length,
i = 0,
changeList = function () {
listItems.eq(i).fadeOut(transition_speed, function () {
i += 1;
if (i === listLen) {
i = 0;
}
listItems.eq(i).fadeIn(transition_speed);
});
};
listItems.not(':first').hide();
setInterval(changeList, change_img_time);
});
and I have another question also: when I import pic with get JSON. the directory in browser is like this:
assets/img/pic1.jpg/
how can I remove the / at the end of directory. because with / in is not shows the pic in browsers
thanks
Try:
if($('#exampleSlider').is(":hover") == true){
return false;
}
I have style id like this
#Myimage {
width: 797px;
height: 317px;
background:url(images/templatemo_header_pizza.jpg) no-repeat;
And I want to change the picture every 5 sec.
I am new to JavaScript and jQuery but the main idea something like this
function ()
{
ImageArray = LoadImage("Baseimage/*.jpg")
while(true)
{
For(i in ImageArray)
{
Myimage.background:url = i;
waitfor(5);
}
}
}
var imgArray = ["image1.jpg","image2.jpg"];
var counter = 0;
function changeImages() {
counter++;
$("#MyImage").css("background-image",'url(' +imgArray[counter] + ')')
if(counter == 1) {
counter = -1;
}
}
setInterval(changeImages,5000)
Attach a Jquery lib. and past that JQuery script in you head section:
$(window).load(function() {
var i =0;
var images = ['image2.png','image3.png','image1.png'];
var image = $('#Myimage');
//Initial Background image setup
image.css('background-image', 'url(image1.png)');
//Change image at regular intervals
setInterval(function(){
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + images [i++] +')');
image.fadeIn(1000);
});
if(i == images.length)
i = 0;
}, 5000);
});
You can use Image to check if the image exists:
$(function () {
var base = "myImage_*.jpg", img, c = 0, ar = [], o = 0;
function recurse () {
img = new Image();
img.src = base.replace('*', ++c);
img.onload = function () {
ar.push(img.src);
recurse();
}
img.onerror = function () {
c = -1;
function r() {
$("yourElement").css("background-image", "url("+ar[c++ >= ar.length ? (c=0) : c]+")");
setTimeout(r, 2000); // 2000 is two seconds
}
}
}
});
Before I get into details, please take a look at the live example where this problem occurs - http://jsfiddle.net/66HFU/ (Script code at the bottom of this post)
Now if you would click on any image at last row, it would display these. However if you would click on upper row images, below row images are shown.
Further investigation shows that for somewhat reason the letter called function selector elements only get binded with event listener while the firstly called functions selector elements do not.
So, I would like to know is there are any ways to make the function call independent so the latter function call does not override first one (if that would fix the problem, of-course)?
The place where the event function gets bind on the element can be found in function f_AddEvents first lines.
And the the main function calls that are used to initialize Light Box is at the bottom of the code like this:
LightBox.init({
selector: "[data-simplbox='demo1']",
boxId: "simplbox"
});
LightBox.init({
selector: "[data-simplbox='demo2']",
boxId: "simplbox",
imageLoadStart: activityIndicatorOn,
imageLoadEnd: activityIndicatorOff
});
All code:
;(function (window, document, undefined) {
var docElem = document.documentElement;
var DomM = (function() {
var f_ToDOMStyle = function (p_Style) {
return p_Style.replace(/\-[a-z]/g, function (p_Style) {
return p_Style.charAt(1).toUpperCase();
});
};
return {
event: {
set: function (p_Element, p_Events, p_Function) {
var i = 0,
j = 0;
p_Events = p_Events.split(" ");
if (!p_Element.length) {
for (i = 0; i < p_Events.length; i++) {
p_Element.addEventListener(p_Events[i], p_Function, false);
}
} else {
for (i = 0; i < p_Element.length; i++) {
for (j = 0; j < p_Events.length; j++) {
p_Element[i].addEventListener(p_Events[j], p_Function, false);
}
}
}
}
},
css: {
set: function (p_Element, p_Style) {
var j;
if (!p_Element.length) {
for (j in p_Style) {
if (p_Style.hasOwnProperty(j)) {
j = f_ToDOMStyle(j);
p_Element.style[j] = p_Style[j];
}
}
} else {
for (var i = 0; i < p_Element.length; i++) {
for (j in p_Style) {
if (p_Style.hasOwnProperty(j)) {
j = f_ToDOMStyle(j);
p_Element[i].style[j] = p_Style[j];
}
}
}
}
}
}
};
}());
var _LightBox = {
f_MergeObjects: function (p_Original, p_Updates) {
for (var i in p_Updates) {
if (p_Updates.hasOwnProperty(i)) {
p_Original[i] = p_Updates[i];
}
}
return p_Original;
},
f_isFunction: function (p_Function) {
return !!(p_Function && p_Function.constructor && p_Function.call && p_Function.apply);
},
f_Initialize: function (p_Options) {
var base = this;
base.m_Options = base.f_MergeObjects(_LightBox.options, p_Options || {});
base.m_Elements = document.querySelectorAll(base.m_Options.selector);
base.m_ElementsLength = base.m_Elements.length - 1;
base.m_Body = document.getElementsByTagName("body")[0];
base.m_CurrentImageElement = false;
base.m_CurrentImageNumber = 0;
base.m_Direction = 1;
base.m_InProgress = false;
base.m_InstalledImageBox = false;
console.log(base.m_Elements);
// Check if hardware acceleration is supported and check if touch is enabled.
base.f_CheckBrowser();
// Adds events.
base.f_AddEvents();
},
f_CheckBrowser: function () {
var base = this,
isTouch = "ontouchstart" in window || window.navigator.msMaxTouchPoints || navigator.maxTouchPoints || false,
vendors = ["ms", "O", "Moz", "Webkit", "Khtml"],
rootStyle = docElem.style,
hardwareAccelerated = false;
if ("transform" in rootStyle) {
hardwareAccelerated = true;
} else {
while (vendors.length) {
if (vendors.pop() + "Transform" in rootStyle) {
hardwareAccelerated = true;
}
}
}
base.browser = {
"isHardwareAccelerated": hardwareAccelerated,
"isTouch": isTouch
};
},
f_AddEvents: function () {
var base = this;
// Add open image event on images.
for (var i = 0; i < base.m_Elements.length; i++) {
(function (i) {
base.m_Elements[i].addEventListener("click", function (event) {
event.preventDefault();
console.log(base.m_Elements[i]);
if (base.f_isFunction(base.m_Options.onImageStart)) {
base.m_Options.onImageStart();
}
base.f_OpenImage(i);
}, false);
})(i);
}
// Resize event for window.
window.addEventListener("resize", function (event) {
event.preventDefault();
base.f_SetImage();
}, false);
// Add keyboard support.
if (base.m_Options.enableKeyboard) {
var keyBoard = {
left: 37,
right: 39,
esc: 27
};
window.addEventListener("keydown", function (event) {
event.preventDefault();
if (base.m_CurrentImageElement) {
if (base.m_InProgress) {
return false;
}
switch (event.keyCode) {
case keyBoard.left:
// If the previous one is out of target range then go to the last image.
if ((base.m_CurrentImageNumber - 1) < 0) {
base.f_OpenImage(base.m_ElementsLength, "left");
} else {
base.f_OpenImage(base.m_CurrentImageNumber - 1, "left");
}
return false;
case keyBoard.right:
// If the next one is out of target range then go to the first image.
if ((base.m_CurrentImageNumber + 1) > base.m_ElementsLength) {
base.f_OpenImage(0, "right");
} else {
base.f_OpenImage(base.m_CurrentImageNumber + 1, "right");
}
return false;
case keyBoard.esc:
base.f_QuitImage();
return false;
}
}
return false;
}, false);
}
// Add document click event.
if (base.m_Options.quitOnDocumentClick) {
document.body.addEventListener("click", function (event) {
var target = event.target ? event.target : event.srcElement;
event.preventDefault();
if (target && target.id != "imagelightbox" && base.m_CurrentImageElement && !base.m_InProgress && base.m_InstalledImageBox) {
base.f_QuitImage();
return false;
}
return false;
}, false);
}
},
f_OpenImage: function (p_WhichOne, p_Direction) {
var base = this,
newFragment = document.createDocumentFragment(),
newImageElement = document.createElement("img"),
target = base.m_Elements[p_WhichOne].getAttribute("href");
if (base.m_CurrentImageElement) {
base.f_RemoveImage();
}
if (base.f_isFunction(base.m_Options.imageLoadStart)) {
base.m_Options.imageLoadStart();
}
base.m_InProgress = true;
base.m_InstalledImageBox = false;
base.m_Direction = typeof p_Direction === "undefined" ? 1 : p_Direction == "left" ? -1 : 1;
newImageElement.setAttribute("src", target);
newImageElement.setAttribute("alt", "LightBox");
newImageElement.setAttribute("id", base.m_Options.boxId);
newFragment.appendChild(newImageElement);
base.m_Body.appendChild(newFragment);
base.m_CurrentImageElement = document.getElementById(base.m_Options.boxId);
base.m_CurrentImageElement.style.opacity = "0";
base.m_CurrentImageNumber = p_WhichOne;
if (base.m_Options.quitOnImageClick) {
base.f_ImageClickEvent = function (event) {
event.preventDefault();
base.f_QuitImage();
};
base.m_CurrentImageElement.addEventListener("click", base.f_ImageClickEvent, false);
}
if (base.browser.isHardwareAccelerated) {
DomM.css.set(base.m_CurrentImageElement, base.f_AddTransitionSpeed(base.m_Options.animationSpeed));
}
base.f_SetImage();
DomM.css.set(base.m_CurrentImageElement, base.f_doTranslateX(50 * base.m_Direction + "px"));
setTimeout(function () {
if (base.browser.isHardwareAccelerated) {
setTimeout(function () {
DomM.css.set(base.m_CurrentImageElement, base.f_doTranslateX("0px"));
}, 50);
}
if (base.f_isFunction(base.m_Options.imageLoadEnd)) {
base.m_Options.imageLoadEnd();
}
}, 20);
setTimeout(function () {
base.m_InProgress = false;
base.m_InstalledImageBox = true;
}, base.m_Options.animationSpeed - 200);
},
f_SetImage: function () {
var base = this,
screenHeight = window.innerHeight || docElem.offsetHeight,
screenWidth = window.innerWidth || docElem.offsetWidth,
tmpImage = new Image(),
imageWidth, imageHeight, imageSizeRatio;
if (!base.m_CurrentImageElement) {
return;
}
tmpImage.onload = function () {
imageWidth = this.width;
imageHeight = this.height;
imageSizeRatio = imageWidth / imageHeight;
if (Math.floor(screenWidth/imageSizeRatio) > screenHeight) {
imageWidth = screenHeight * imageSizeRatio * 0.7;
imageHeight = screenHeight * 0.7;
} else {
imageWidth = screenWidth * 0.7;
imageHeight = screenWidth / imageSizeRatio * 0.7;
}
DomM.css.set(base.m_CurrentImageElement, {
"top": ((screenHeight - imageHeight) / 2) + "px",
"left": ((screenWidth - imageWidth) / 2) + "px",
"width": Math.floor(imageWidth) + "px",
"height": Math.floor(imageHeight) + "px",
"opacity": 1
});
};
tmpImage.src = base.m_CurrentImageElement.getAttribute("src");
},
f_RemoveImage: function () {
var base = this;
if (base.m_CurrentImageElement) {
if (base.f_isFunction(base.m_Options.quitOnImageClick)) {
base.m_CurrentImageElement.removeEventListener("click", base.f_ImageClickEvent, false);
}
base.m_CurrentImageElement.parentNode.removeChild(base.m_CurrentImageElement);
base.m_CurrentImageElement = false;
}
return false;
},
f_QuitImage: function () {
var base = this;
if (base.m_CurrentImageElement) {
setTimeout(function () {
DomM.css.set(base.m_CurrentImageElement, {
"opacity": 0,
"transition": ("opacity " + base.m_Options.fadeOutSpeed + "ms ease")
});
setTimeout(function () {
base.f_RemoveImage();
if (base.f_isFunction(base.m_Options.onImageQuit)) {
base.m_Options.onImageQuit();
}
}, base.m_Options.fadeOutSpeed);
}, 20);
}
},
f_IsValidSource: function (p_Src) {
return new RegExp().test(p_Src);
},
f_doTranslateX: function (p_Pixels) {
return {
"-webkit-transform": "translateX(" + p_Pixels + ")",
"-moz-transform": "translateX(" + p_Pixels + ")",
"-o-transform": "translateX(" + p_Pixels + ")",
"-ms-transform": "translateX(" + p_Pixels + ")",
"transform": "translateX(" + p_Pixels + ")"
};
},
f_AddTransitionSpeed: function (p_Speed) {
var base = this;
return {
"-webkit-transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease",
"-moz-transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease",
"-o-transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease",
"transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease"
};
}
};
_LightBox.options = {
selector: "[data-imagelightbox]",
boxId: "imagelightbox",
allowedTypes: "png|jpg|jpeg|gif",
quitOnImageClick: true,
quitOnDocumentClick: true,
enableKeyboard: true,
animationSpeed: 750,
fadeInSpeed: 500,
fadeOutSpeed: 200,
imageLoadStart: function () {},
imageLoadEnd: function () {},
onImageQuit: function () {},
onImageStart: function () {}
};
LightBox.init = function (p_Options) {
_LightBox.f_Initialize(p_Options);
};
})(window, document, window.LightBox = window.LightBox || {});
var activityIndicatorOn = function () {
var newE = document.createElement("div"),
newB = document.createElement("div");
newE.setAttribute("id", "imagelightbox-loading");
newE.appendChild(newB);
document.body.appendChild(newE);
},
activityIndicatorOff = function () {
var elE = document.getElementById("imagelightbox-loading");
elE.parentNode.removeChild(elE);
};
LightBox.init({
selector: "[data-simplbox='demo1']",
boxId: "simplbox"
});
LightBox.init({
selector: "[data-simplbox='demo2']",
boxId: "simplbox",
imageLoadStart: activityIndicatorOn,
imageLoadEnd: activityIndicatorOff
});
Your code is almost working. What you handled badly is the fact that you can perform several init. On each init, you overwrite some items, especially with this line :
base.m_Elements = document.querySelectorAll(base.m_Options.selector);
So base.m_Elements will only have the elements of the last init.
( Based on the name 'init' i wonder if the real use case wouldn't be to allow just one call of init... )
Quick-fix is to do one single init with :
LightBox.init({
selector: "[data-simplbox='demo1'],[data-simplbox='demo2']",
boxId: "simplbox"
});
(erase the two calls to init)
And here it works.
http://jsfiddle.net/gamealchemist/66HFU/1/
So i guess either you want to support several init, or (easier to maintain in fact), throw exception on multiple init and expect the lib user to write the right selector in the single init call.
Edit : Super quick fix for your issue : rather than having LightBox as a singleton, have it as a Class :
function LightBox( initArguments ) {
// something like what was done in init
}
LightBox.prototype = {
f_RemoveImage : function() {
} ,
f_OpenImage : function( ..., ... ) {
} ,
...
}
then you can call with no issue :
var demo1LB = new LightBox({ selector: "[data-simplbox='demo1']",
boxId: "simplbox" });
var demo2LB = new LightBox({ selector: "[data-simplbox='demo2']",
boxId: "simplbox" });
Below is some code that has no jquery, but it is not working:
function start() {
var img = 0,
pic = ['nature', 'grass', 'earth', 'fall2', 'waterfall'],
slider = document.getElementsByClassName('slide_img'),
timerID = 0,
delay = 4000;
function back() {
img--;
if (img <= 0) {
img = pic.length - 1;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
function go() {
img++;
if (img >= pic.length) {
img = 0;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
document.getElementById('back').onclick = function() {
back();
}
document.getElementById('go').onclick = function() {
go();
}
slider.onmouseenter = function() {
clearTimeout(timerID);
}
document.getElementById('go').onmouseenter = function() {
clearTimeout(timerID);
}
document.getElementById('back').onmouseenter = function() {
clearTimeout(timerID);
}
slider.onmouseleave = function() {
clearTimeout(timerID);
auto();
}
function auto() {
timerID = setTimeout(function () {
go();
auto();
}, delay);
}
auto();
}
Here is what it is in jquery, this one works:
$('document').ready(function() {
var img = 0,
pic = ['nature', 'grass', 'earth', 'fall2', 'waterfall'],
slider = $('img.slide_img'),
timerID = 0,
delay = 4000;
function back() {
img--;
if (img <= 0) {
img = pic.length - 1;
}
slider.attr('src', 'pictures/' + pic[img] + '.jpg');
}
function go() {
img++;
if (img >= pic.length) {
img = 0;
}
slider.attr('src', 'pictures/' + pic[img] + '.jpg');
}
$('button#back').on('click', function() {
back();
});
$('button#go').on('click', function() {
go();
});
$(slider).on('mouseenter', function () {
clearTimeout(timerID);
});
$('button#go').on('mouseenter', function () {
clearTimeout(timerID);
});
$('button#back').on('mouseenter', function () {
clearTimeout(timerID);
});
$(slider).on('mouseleave', function () {
clearTimeout(timerID);
auto();
});
function auto() {
timerID = setTimeout(function () {
go();
auto();
}, delay);
}
auto();
});
What am i doing wrong, why is the first one not working. Im am trying to get rid of jquery so i dont have to include the source file.
You are not executing onload
try
var img = 0,
pic = ['nature', 'grass', 'earth', 'fall2', 'waterfall'],
slider,
timerID = 0,
delay = 4000;
window.onload=function() {
slider = document.getElementsByClassName('slide_img');
document.getElementById('back').onclick = function() {
back();
}
document.getElementById('go').onclick = function() {
go();
}
slider.onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('go').onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('back').onmouseover = function() {
clearTimeout(timerID);
}
slider.onmouseout = function() {
clearTimeout(timerID);
auto();
}
auto();
}
function auto() {
timerID = setTimeout(function () {
go();
auto();
}, delay);
}
function back() {
img--;
if (img <= 0) {
img = pic.length - 1;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
function go() {
img++;
if (img >= pic.length) {
img = 0;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
Use "onmouseover" and onmouseout" for canonical events:
slider.onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('go').onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('back').onmouseover = function() {
clearTimeout(timerID);
}
slider.onmouseout = function() {
clearTimeout(timerID);
auto();
}
And don't forget to define "slider" (the initial part is missing in your script):
var slider = document.querySelector('img.slide_img');
<body onload="start"></body>
The JavaScript start doesn't do anything. If you want to call a function, then you need to follow it with ().
This is a rather obtrusive way to deal with event handler assignment though. It is generally preferred to assign such things with JavaScript:
addEventListener('load', start);
See MDN for compatibility notes.
However, you don't have anything in your code that depends on the entire document being loaded. So you can simply:
<script>
start();
</script>
</body>
at the end of your document.
(You can put the whole script there for that matter, and keep it in an external file).
Hi I have wrote this code and it suppose to move the object every 3000 ms after clicking on the object, but some how the time its not working, can anyone tell me what I am doing wrong, I am just learning javascript; thank you very much
function move1() {
var im1 = document.images[0];
im1.onclick = function() {
im1.style.left = parseInt(im1.style.left) + 1 + "px";
}
}
function move2() {
var im2 = document.images[1];
im2.onclick = function() {
im2.style.left = parseInt(im2.style.left) + 10 + "px";
}
}
window.onload = function() {
setInterval(move1, 100);
setInterval(move2, 3000);
}
You're doing it the other way round. Every 3000ms you make it possible to move the image by 1px when clicking on it.
function move(el, ms, px) {
/* moves the el every ms by px
returns the interval id to clear the movement */
return setInterval(function() {
el.style.left = parseInt(el.style.left) + px + "px";
}, ms);
}
window.onload = function() {
var im0 = document.images[0];
var im1 = document.images[1];
im0.onclick = function() {
move(im0, 100, 1);
};
im1.onclick = function() {
move(im1, 3000, 10);
};
}
Your move function registers the image on click, but doesn't actually do any moving until the user clicks. What you want is more like this:
function move1() {
var im1 = document.images[0];
im1.style.left = parseInt(im1.style.left) + 1 + "px";
}
function move2() {
var im2 = document.images[1];
im2.style.left = parseInt(im2.style.left) + 10 + "px";
}
window.onload = function() {
var im2 = document.images[1];
im2.onclick = function() {
setInterval(move2, 3000);
}
im1.onclick = function() {
setInterval(move1, 100);
}
}