Any Shorter way for jquer .eq selector? - javascript

startSliding($("div").eq(0));
startSliding($("div").eq(1));
startSliding($("div").eq(2));
I would like to know if there is a different way to add only one code instead of repeating eq selector every time.
startSliding($("div").eq(unlimited));
The full js file is:
startSliding($("div").eq(0));
startSliding($("div").eq(1));
startSliding($("div").eq(2));
startSliding($("div").eq(3));
function startSliding (div) {
var i = 0;
var tid = null;
var sec = 1/3; // <- you want 1 here
var images = $("img", div).map(function () {
return $(this).attr("src");
}).get();
$("img:gt(0)", div).remove();
$("img", div).hover(function () {
var $this = $(this);
tid = setInterval(function () {
i = (i + 1) % images.length;
$this.attr("src", images[i]);
}, 1000 * sec);
}, function () {
clearInterval(tid);
$(this).attr("src", images[0]);
});
}
I got this way in another question from some one who helped me to much but now working on Im getting more ideas on my project, and the DIVs that I have in page are changing, sometimes in a page I have 10 divs sometimes 50.Adding eq selector for each div will effect in pagespeed too. so if there is a shorter code which does the same job would be great to know.I'm a newbea with javascript :(
https://jsfiddle.net/jhudrp8v/11/
Thank You!

It's very simple to do so.
You have to just use .each() jquery method.
Check below code snippet for the same -
// Added code
let elem = $('div.someclass');
elem.each(function(i) {
startSliding(elem.eq(i));
});
// Your code
function startSliding (div) {
var i = 0;
var tid = null;
var sec = 1/3; // <- you want 1 here
var images = $("img", div).map(function () {
return $(this).attr("src");
}).get();
$("img:gt(0)", div).remove();
$("img", div).hover(function () {
var $this = $(this);
tid = setInterval(function () {
i = (i + 1) % images.length;
$this.attr("src", images[i]);
}, 1000 * sec);
}, function () {
clearInterval(tid);
$(this).attr("src", images[0]);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someclass">
<img height="150" src="https://i.stack.imgur.com/BDcMh.gif">
<img height="150" src="https://i.stack.imgur.com/vfQCT.gif">
<img height="150" src="https://i.stack.imgur.com/MbEgw.gif">
<img height="150" src="https://i.stack.imgur.com/uCCEw.gif">
<img height="150" src="https://i.stack.imgur.com/iO6QE.gif">
</div>
<div class="someclass">
<img height="150" src="https://i.stack.imgur.com/BDcMh.gif">
<img height="150" src="https://i.stack.imgur.com/vfQCT.gif">
<img height="150" src="https://i.stack.imgur.com/MbEgw.gif">
<img height="150" src="https://i.stack.imgur.com/uCCEw.gif">
<img height="150" src="https://i.stack.imgur.com/iO6QE.gif">
</div>
<div class="someclass">
<img height="150" src="https://i.stack.imgur.com/BDcMh.gif">
<img height="150" src="https://i.stack.imgur.com/vfQCT.gif">
<img height="150" src="https://i.stack.imgur.com/MbEgw.gif">
<img height="150" src="https://i.stack.imgur.com/uCCEw.gif">
<img height="150" src="https://i.stack.imgur.com/iO6QE.gif">
</div>
<div class="someclass">
<img height="150" src="https://i.stack.imgur.com/BDcMh.gif">
<img height="150" src="https://i.stack.imgur.com/vfQCT.gif">
<img height="150" src="https://i.stack.imgur.com/MbEgw.gif">
<img height="150" src="https://i.stack.imgur.com/uCCEw.gif">
<img height="150" src="https://i.stack.imgur.com/iO6QE.gif">
</div>
For more info on .each() refer https://api.jquery.com/eq/
Hope this will help you :)

Related

Multiple image sliders in HTML

Please help. This div and script works only once. I want to separate slideshows one after the other ,with different images. But if I try to write this script more than once the slideshow doesn't work. I tried everything I can. The div and the script works fine when it comes to a page with only one age slideshow.but when it's more than one it doesn't.
<div >
<img alt="kandy" src="kandy4.jpg" style="width:1000"
height="500" class="kandy">
<img alt="kandy" src="kandy.jpg" style="width:1000"
height="500" class="kandy">
<img alt="kandy" src="kandy2.jpg" style="width:1000"
height="500" class="kandy">
<img alt="kandy" src="kandy3.jpg" style="width:1000"
height="500" class="kandy">
</div>
<script>
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("kandy");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 3000); // Change image every 3
seconds
}
</script>
<div >
<img alt="ella" src="ella4.jpg" style="width:1000"
height="500" class="ella">
<img alt="ella" src="ella.jpg" style="width:1000"
height="500" class="ella">
<img alt="ella" src="ella2.jpg" style="width:1000"
height="500" class="ella">
<img alt="ella" src="ella3.jpg" style="width:1000"
height="500" class="ella">
</div>
<script>
var myIndex = 0;
carousel();
function carousel() {
var j;
var y = document.getElementsByClassName("ella");
for (j = 0; j < y.length; j++) {
y[j].style.display = "none";
}
myIndex++;
if (myIndex > y.length) {myIndex = 1}
y[myIndex-1].style.display = "block";
setTimeout(carousel, 3000); // Change image every 3
seconds
}
</script>
I'm not sure I fully understood the question but perhaps the following might be of use? A slightly simplified layout from the orginal but same content - except for changes made to the style attribute which was incorrect.
If the carousel function accepted arguments then you can call it many times with different arguments - as it was a later calling would like overwrite the previous invocation of the function.
<div>
<img alt="kandy" src="kandy4.jpg" width='1000px' height='500px' class="kandy">
<img alt="kandy" src="kandy.jpg" width='1000px' height='500px' class="kandy">
<img alt="kandy" src="kandy2.jpg" width='1000px' height='500px' class="kandy">
<img alt="kandy" src="kandy3.jpg" width='1000px' height='500px' class="kandy">
</div>
<div>
<img alt="ella" src="ella4.jpg" width='1000px' height='500px' class="ella">
<img alt="ella" src="ella.jpg" width='1000px' height='500px' class="ella">
<img alt="ella" src="ella2.jpg" width='1000px' height='500px' class="ella">
<img alt="ella" src="ella3.jpg" width='1000px' height='500px' class="ella">
</div>
<script>
/* pass in whatever class as an argument */
const carousel=function( _classname, _index, _time ){
let col=document.getElementsByClassName( _classname );
Array.prototype.slice.call( col ).forEach(function(e){
e.style.display='none';
});
if( _index > col.length - 1 ) _index=0;
col[ _index ].style.display='block';
console.info( col[ _index ] );
setTimeout( function(){
carousel.call( this, _classname, _index, _time );
},_time * 1000 );
_index++;
}
carousel('kandy',0,3);
carousel('ella',0,3);
</script>

onclick get index of image in for loop javascript

onclick get image index in for loop in javascript not jquery, the main problem here is that i can't access any global variable in function
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title></title>
</head>
<body>
<img src="images/2.jpg" width="350" height="250">
<img src="images/3.jpg" width="350" height="250">
<img src="images/4.jpg" width="350" height="250">
<img src="images/5.jpg" width="350" height="250">
<img src="images/6.jpg" width="350" height="250">
<img src="images/7.jpg" width="350" height="250">
<script type="text/javascript" src="scripts/script.js"></script>
</body>
</html>
/*external javascript file code */
var img = document.images;
var i;
for(i=0;i<img.length;i++){
img[i].src = "images/1.jpg";
//after changing image src i just want to show index of clicked image
img[i].onclick = function(){
alert("i m img "+ i);
console.log(i);
}
console.log(i);
}
You can store the index in your own html attribute like index-data using setAttribute and getAttribute:
var img = document.images;
var i;
for (i = 0; i < img.length; i++) {
img[i].src = "images/1.jpg";
img[i].setAttribute("index-data", i);
//after changing image src i just want to show index of clicked image
img[i].onclick = function() {
var index = this.getAttribute("index-data");
console.log(index);
}
}
<img src="images/2.jpg" width="350" height="250">
<img src="images/3.jpg" width="350" height="250">
<img src="images/4.jpg" width="350" height="250">
<img src="images/5.jpg" width="350" height="250">
<img src="images/6.jpg" width="350" height="250">
<img src="images/7.jpg" width="350" height="250">
You can use the attribute dataset to store the current index.
var img = document.images;
var i;
var images = ['https://www.hrexaminer.com/wp-content/uploads/2016/10/2016-10-11-hrexaminer-stackoverflow-6-xxl-sq-250px.png', 'https://i.stack.imgur.com/G2FO1.jpg?s=48&g=1']
for (i = 0; i < img.length; i++) {
img[i].src = images[i];
img[i].dataset.index = i;
img[i].onclick = function() {
var index = this.dataset.index;
console.log(index);
}
}
<img src="" width="100" height="100">
<img src="" width="100" height="100">
This is a classical closure problem inside a loop.
The simple solution to this problem is to wrap the code block which has
indefinite execution, inside a IIFE block.
read about it here : Javascript closures
for(i=0;i<img.length;i++){
img[i].src = "images/1.jpg";
(function(index){
img[index].onclick = function(){
alert("i m img "+ index);
console.log(index);
}
})(i)
}

Changing the dimensions of element

I want to change many elements (figcaption) dimensions to img dimensions with jquery
plz help me
var width = $("div[caption='true'] img").attr("width");
var height = $("div[caption='true'] img").attr("height");
$("div[caption='true'] figcaption").css("width",width);
$("div[caption='true'] figcaption").css("height",height);
jsfiddle link
Try this:
$(function() {
$("div[caption='true']").each(function() {
var $this = $(this);
var image = $this.find('img')
var width = image.width();
var height = image.height();
$this.find('figcaption').width(width).height(height);
});
});
jsFiddle: http://jsfiddle.net/8ge1wvpt/11/
Your current code is setting each figcaption's height and width to that of the first image. Try this:
$(document).ready( function() {
$("div[caption='true']").each(function() {
var $this = $(this);
var width = $("img", $this).attr("width");
var height = $("img", $this).attr("height");
$("figcaption", $this).css({"height":height, "width":width});
});
});
DEMO
Snippet below:
$(document).ready( function() {
$("div[caption='true']").each(function() {
var $this = $(this);
var width = $("img", $this).attr("width");
var height = $("img", $this).attr("height");
$("figcaption", $this).css({"height":height, "width":width});
});
});
*{margin:0;padding:0;}
.imgs{position:relative;}
figcaption{position:absolute;top:0;
background-color:rgba(0,0,0,0.4);}
figcaption h3{text-align:center;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="imgs" caption="true">
<img src="http://goo.gl/uRvjRS" width="200" height="250" alt=""/>
<figcaption>
<h3>IMGs Caption 1</h3>
</figcaption>
</div>
<div class="imgs" caption="true">
<img src="http://goo.gl/uRvjRS" width="100" height="100" alt=""/>
<figcaption>
<h3>IMGs Caption 2</h3>
</figcaption>
</div>
<div class="imgs" caption="true">
<img src="http://goo.gl/uRvjRS" width="300" height="200" alt=""/>
<figcaption>
<h3>IMGs Caption 3</h3>
</figcaption>
</div>
You can do it by using a function to fill in the css value:
$(document).ready( function() {
$("img + figcaption")
.css("width",function() { return $(this).prev().attr("width");})
.css("height",function() { return $(this).prev().attr("height"); });
});
This will match any <img> followed by <figcaption> - there is no need for the caption="true" attribute, unless you are using it for something else.

Stuck with mootools script. Image autochange

<div id="contentimage">
<img src="1.jpg" class="activeimage" />
<img src="2.jpg" style="opacity: 0;" />
<img src="3.jpg" class="last" style="opacity: 0;" />
</div>
<script>
window.addEvent('domready', function() {
var fx = function() {
var activeimage = $$('img.activeimage');
if(!activeimage.hasClass('last')) {
var next = activeimage.getNext('img');
activeimage.toggleClass('activeimage');
next.toggleClass('activeimage');
activeimage.morph({'opacity':'0'});
next.morph({'opacity':'1'});
} else {
var next = $('contentimage').getFirst('img');
activeimage.toggleClass('activeimage');
next.toggleClass('activeimage');
activeimage.morph({'opacity':'0'});
next.morph({'opacity':'1'});
}
}
fx.periodical(3000);
});
</script>
I just can't understand why this :
if(!activeimage.hasClass('last'))
always returns false ? I tried to check it with "alert", and it was all good, but when it comes to this line - it goes not like I expected.
Use this instead:
var activeimage = document.getElement('img.activeimage');
Otherwise $$ will get a family and you cannot apply .hasClass() like that.
Demo here (check console after some seconds)

Adding Slide show with JavaScript is messing up my divs

I am not too experienced with JavaScript.
I have created a website with 5 divs on the container. When I added the Slideshow with JavaScript all the images jump to the top and the image I use as header for the site becomes another image from the slideshow.
I tried assigning a class to the images on the slideshow, but I dont know how to incorporate this to the code on JavaScript so that it only focuses on those (instead of all the images on my page).
(THANKS A LOT IF ANYONE CAN HELP!!! I am not being lazy, I just can not seem to find the answer!!!)
Here is the code:
<style type="text/css">
body {
background-image: url(layout/background.png);
}
img{
-webkit-transition-property:opacity;
-webkit-transition-duration:5s;
position:absolute;
width:320;
height:auto;
}
img.fade-out{opacity:0;}
img.fade-in{opacity:1;}
</style>
</head>
<body>
<div id="container">
<div id="header">
<br>
<ul>
<li><img src="main-menu4.gif" width="984" height="290" ></li>
</ul>
</div>
<div id="main_image">
<h1>Events</h1>
<br>
<img class="slideshow" src="hotdog.jpeg" width="450" height="auto" >
<img src="girlonslide.jpeg" width="450" height="auto" class="slideshow">
<img src="games/extremefun.jpg" width="450" height="auto" class="slideshow">
<img src="games/climbing.jpeg" width="450" height="auto" class="slideshow">
<img src="games/cartgame.jpeg" width="450" height="auto" class="slideshow">
<img src="pizza.JPG" width="450" height="auto" class="slideshow">
<script>
var interval = 4 * 20; //Seconds between change
var images = document.getElementsByTagName("img");
var imageArray = [];
var imageCount = images.length;
var current = 0;
var randomize = function(){
return (Math.round(Math.random() * 3 - 1.5));
}
for(var i = 0; i < imageCount; i++){
images[i].className = 'fade-out';
imageArray[i] = images [i];
}
imageArray.sort(randomize);
var fade = function() {
imageArray[current++].className = 'fade-out';
if(current == imageCount){
current = 0;
imageArray.sort(randomize);
}
imageArray[current].className = 'fade-in';
setTimeout(fade, interval * 100);
};
fade();
</script>
</body>
</html>
I really dont know what I am doing wrong!
You seem to be targeting all the image tags in your page. You need to limit that to only the images in your div#main_image.
To do that replace
var images = document.getElementsByTagName("img");
with
var images = document.getElementById("main_image").getElementsByTagName("img");

Categories