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.
Related
I am trying to make a script that will take the images from one div element and put it to div rndmImage randomly on button click, I should see images when document is loaded, but the new div where images should go after click must be empty until click heapends. And I need only JavaScript, no jQuery, alse i can not change the html, and it has to work for any number of images. So if you have some ideas that would be great. Here's my code.
window.addEventListener('load', start, false);
function start() {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('ekran');
var pictures = document.getElementsByTagName('img');
var choose = Math.floor(Math.random()*pictures.length);
butt.addEventListener('click', menjaj, false);
function menjaj(e) {
var new = e.button;
var img = [];
for(var i = 0; i< pictures.length; i++) {
var dodaj = img[i];
img.push(dodaj);
}
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
<body>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
</body>
This is a working snippet of your code:
window.addEventListener('load', start, false);
function start () {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('rndmImage')[0]; //Change selector to existing class and select the first (the only) one
var pictures = document.getElementsByTagName('img');
butt.addEventListener('click', menjaj, false);
function menjaj (e) {
// var new = e.button;// 'new' is reserved word in JS, you can't use it as variable name
// var btn = e.button;// but this line is useless
var choose = Math.floor(Math.random() * pictures.length); //better move this line inside this function to get rundom image every button clicks
var img = document.createElement('img'); //creates new img tag
img.src = pictures[choose].src;
rnImg.innerHTML = ''; //to delete previous image
rnImg.appendChild(img);
// var img = []; //useless lines of code
// for(var i = 0; i< pictures.length; i++) {
// var dodaj = img[i];
// img.push(dodaj);
// }
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
welcome to StackOverflow!
I would first hide the .wrapper > div img as that will prevent the images to show, then, append a data-pos to help select the position and simply randomize them and pick the src to show on the placeholder
and remember that you have a <div> as placeholder, so you can't assign src, only if you change it to <img>
so, something like this 😊
function chooseImg() {
// get total images available
var totalImages = document.querySelectorAll('.wrapper > div img').length
log('totalImages', totalImages)
// get a random position
var rndPosition = Math.floor(Math.random() * totalImages)
log('rndPosition', rndPosition)
// get hold of the image for such position
var rndImage = document.querySelector('.wrapper > div img[data-pos="' + rndPosition + '"]')
log('rndImage', rndImage)
// assign the source to the DIV
document.querySelector('.rndmImage').style = 'background-image: url("' + rndImage.src + '")'
}
function log(txt, obj) {
console.log(txt, obj)
}
.wrapper > div img {
display: none;
}
.rndmImage {
background-size: contain;
background-repeat: no-repeat;
width: 100px;
height: 100px;
}
<div class="wrapper">
<div>
<img data-pos="0" src="https://randomwordgenerator.com/img/picture-generator/54e5d2434953a514f1dc8460962e33791c3ad6e04e507440742f7cd09645cc_640.jpg" alt="leto1">
<img data-pos="1" src="https://randomwordgenerator.com/img/picture-generator/54e2d1404a57a814f1dc8460962e33791c3ad6e04e5074417c2d78d19f44c4_640.jpg" alt="leto2">
<img data-pos="2" src="https://randomwordgenerator.com/img/picture-generator/57e2d5444851a414f1dc8460962e33791c3ad6e04e50744172287ad2914fc4_640.jpg" alt="leto3">
<img data-pos="3" src="https://randomwordgenerator.com/img/picture-generator/51e8d0444f56b10ff3d8992cc12c30771037dbf85254794e722c73d19245_640.jpg" alt="leto4">
<img data-pos="4" src="https://randomwordgenerator.com/img/picture-generator/53e4d2464a56a914f1dc8460962e33791c3ad6e04e507440722d7cd39345c1_640.jpg" alt="leto5">
<img data-pos="5" src="https://randomwordgenerator.com/img/picture-generator/57e9dc434b5ba414f1dc8460962e33791c3ad6e04e50744172297bd5934cc4_640.jpg" alt="leto6">
<img data-pos="6" src="https://randomwordgenerator.com/img/picture-generator/55e1dc4b4254ad14f1dc8460962e33791c3ad6e04e507440722d72d09249c7_640.jpg" alt="leto7">
<img data-pos="7" src="https://randomwordgenerator.com/img/picture-generator/57e9d4474e54a814f1dc8460962e33791c3ad6e04e50744172297cdd974cc0_640.jpg" alt="leto8">
<img data-pos="8" src="https://randomwordgenerator.com/img/picture-generator/53e6dc404951b10ff3d8992cc12c30771037dbf852547848702e7ed19348_640.jpg" alt="leto9">
</div>
<div>
<button type="button" onclick="chooseImg()">choose</button>
</div>
<div class="rndmImage"></div>
</div>
<div class="wrapper">
<img src="../Assets1/Image/1.svg" alt="" />
<img src="../Assets1/Image/2.svg" alt="" />
<img src="../Assets1/Image/3.svg" alt="" />
</div>
<button>Click</button>
<div class="randomImageContainer"></div>
const button = document.querySelector('button');
button.addEventListener('click', randomImage);
function randomImage() {
const image = document.querySelectorAll('.wrapper > img');
const randomImageContainer = document.querySelector('.randomImageContainer');
let randomNumber = Math.floor(Math.random() * image.length);
const img = document.createElement('img');
img.src = image[randomNumber].src;
randomImageContainer.appendChild(img);
}
You can do this with plain javascript like this:
document.querySelector("button").addEventListener("click", () => {
var imgElements = document.querySelectorAll(".wrapper img");
document.querySelector(".rndmImage").innerHTML = imgElements[Math.floor(Math.random() * imgElements.length)].outerHTML;
});
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
If you're able to use randojs, you can even simplify the randomness and make it all cryptographically secure like this:
document.querySelector("button").addEventListener("click", () => document.querySelector(".rndmImage").innerHTML = rando(document.querySelectorAll(".wrapper img")).value.outerHTML);
<script src="https://randojs.com/2.0.0.js"></script>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
Try this:
this is my image in HTML file
<snap id="image" class="btn btn-warning" onclick="changeImage()">Image</snap>
<image id="imagechange" src="https://picsum.photos/200/300" ></image>
my javascript file
imgcount = 0;
function changeImage() {
document.getElementById("imagechange").src =
"https://picsum.photos/200/" + (300 + imgcount);
imgcount++;
}
everytime you click button you get a new image
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 :)
Basically, when an image inside the div is clicked once, the clicked image's position needs to move to become the very first image inside the div, and the rest of the images have to shuffle over one spot. I can't use jQuery for this.
<div>
<img src="images/yellow.jpg">
<img src="images/blue.jpg">
<img src="images/red.jpg">
<img src="images/green.jpg">
<img src="images/black.jpg">
</div>
I tried the following in javascript:
document.addEventListener('click', function() {
for(var i = 0; i < document.images.length; i++) {
//what code here?
}
}, false);
Simply remove the clicked element using removeChild() and insert the same as new element.
var img_wrapper = document.getElementById('img_wrapper');
var el = img_wrapper.getElementsByTagName('img');
for(var i = 0; i < el.length; i++) {
el[i].addEventListener("click", shuffleImages);
}
function shuffleImages(e) {
var selected_img = e.target;
img_wrapper.removeChild(selected_img);
img_wrapper.insertBefore(selected_img, img_wrapper.firstChild);
}
<div id="img_wrapper">
<img src="http://via.placeholder.com/100x100&&text=1" />
<img src="http://via.placeholder.com/100x100&&text=2" />
<img src="http://via.placeholder.com/100x100&&text=3" />
<img src="http://via.placeholder.com/100x100&&text=4" />
<img src="http://via.placeholder.com/100x100&&text=5" />
</div>
Simply detach the clicked image from parent, then reinsert it at the beginning. You can also share handler and use the keyword this to identify the clicked image.
var img = document.querySelectorAll("img");
for(var i = 0; i < img.length; i++) img[i].addEventListener("click", clickHandler);
function clickHandler() {
var parent = this.parentNode; // ref. parent for later
parent.removeChild(this); // remove clicked image from DOM
parent.insertBefore(this, parent.firstChild); // reinsert clicked image first
}
<div style="font-size:0">
<img src="http://lorempixel.com/64/64?1">
<img src="http://lorempixel.com/64/64?2">
<img src="http://lorempixel.com/64/64?3">
<img src="http://lorempixel.com/64/64?4">
<img src="http://lorempixel.com/64/64?5">
</div>
Append the clicked image to first position.
https://jsfiddle.net/vineeshmp/ndndhc9j/
<div id="container">
<img src="http://4.bp.blogspot.com/-M7FEplJcjOM/UE0-vV3HUcI/AAAAAAAAEBA/-nTyQ8spBJc/s1600/Number-One.png" width="100" height="100">
<img src="https://upload.wikimedia.org/wikipedia/commons/f/f7/MetroDF_Linea_2.jpg" width="100" height="100">
<img src="http://www.hotel-r.net/im/hotel/gb/number-three-20.png" width="100" height="100">
<img src="http://1.bp.blogspot.com/-mFRbag9oIwM/URcr_79sUtI/AAAAAAAAIFA/ezJStcA1ZpM/s320/4.jpg" width="100" height="100">
</div>
document.addEventListener('click', function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
var container = document.getElementById("container");
container.insertBefore(target, container.firstChild);
}, false);
another way to move clicked image to first position
document.querySelectorAll('img').forEach(function(item) {
item.addEventListener('click', function() {
var imgs = document.querySelectorAll('img');
firstimg = imgs[0].src;
for(var i = 1; i < imgs.length; i++) {
if(imgs[i].src == this.src) {
imgs[0].src = this.src;
imgs[i].src = firstimg;
}
}
}, false);
});
<div>
<img src="http://lorempixel.com/64/64?1">
<img src="http://lorempixel.com/64/64?2">
<img src="http://lorempixel.com/64/64?3">
<img src="http://lorempixel.com/64/64?4">
<img src="http://lorempixel.com/64/64?5">
</div>
I'm working on a web project that has a changing background image every few seconds. Problem is I don't know how to get the first image to return after all images are finished rotating. After the third image the screen goes white.
html :
<section class="slideshow">
<img src="img/img1.png" class="bgM show"/>
<img src="img/img2.png" class="bgM"/>
<img src="img/img3.jpg" class="bgM"/>
</section>
javascript
function switch() {
var $active = $('.slideshow IMG.show');
var $next = $active.next();
var $images = new Array();
var $length = $images.length;
$next.addClass('show');
$active.removeClass('show');
if ($images[$length].hasClass('show')) {
$images[0].addClass('show');
}
}
$(function() {
setInterval( "switch()", 8000 );
});
jsFiddle Demo
No need for the extra code. Just use an iterator with mod for the set of image elements.
$(function() {
var slide = $(".slideshow"), cur = 0;
setInterval(function(){
$('.show',slide).removeClass('show');
$('img',slide).eq((++cur)%3).addClass('show');
}, 1000 );//using 1000 just for demo purposes
});
.slideshow img.show{
border:2px solid red;
display:block;
}
.slideshow img{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="slideshow">
<img src="http://placehold.it/350x150" class="bgM show"/>
<img src="http://placehold.it/250x150" class="bgM"/>
<img src="http://placehold.it/150x150" class="bgM"/>
</section>
The first major issue is that your function switch is a reserved word (ie choose another name [I chose switch_images]).
Next you can check to see if the "next" image exists (.length). If it doesn't then set it to the first image in the slideshow:
<section class="slideshow">
<img src="img/img1.png" class="bgM show"/>
<img src="img/img2.png" class="bgM"/>
<img src="img/img3.jpg" class="bgM"/>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function switch_images() {
var $active = $('.slideshow IMG.show');
var $next = $active.next();
if(!$next.length){
$next = $('.slideshow IMG:first');
}
$active.removeClass('show');
$next.addClass('show');
}
$(function() {
setInterval( "switch_images()", 8000 );
});
</script>
I am trying to make a simple image gallery like this. http://dimsemenov.com/plugins/royal-slider/#image-gallery When I click a thumbnail image, image element will create and loading image will appear a little time and created element will slide in the visible area.At last old image elment will remove.
<div id="imageGallery" style="overflow:visible;display:block;">
<div class="preview">
<div id="content" style="width:640px;height:420px;">
<img id="main-Image" alt="" src="../../baContent/image1.jpg" style="display:inline; top:0;left:0;" />
</div>
</div>
<div id="thumbnails">
<a class="thumbnail" href="../../baContent/image1.jpg"><img alt="Image 1" src="../../baContent/image1-thumb.jpg"></a>
<a class="thumbnail" href="../../baContent/image2.jpg"><img alt="Image 2" src="../../baContent/image2-thumb.jpg"></a>
</div>
$(document).ready(function () {
$(".thumbnail").click(function () {
$("#mainImage").animate({ "left": "-640px" }, "fast");
$('#preview').css('background-image', "url('../../baContent/spinner.gif')");
var img = $("<img style='left:640px;display:none;' />").attr('src', this.href).load(function () {
$('#mainImage').attr('src', img.attr('src'));
$('#preview').css('background-image', 'none');
$(this).parent().prevAll().remove();
$("#mainImage").animate({ "left": "-640px" }, "fast");
});
});
});
I wrote a few code but had no success. Any ideas or tutorials?
Try :
$(document).ready(function () {
$(".thumbnail").click(function () {
$('#main-Image').hide();
$('#preview').css('background-image', "url('../../baContent/spinner.gif')");
var imgSrc = $(this).attr('href');
var img = $("<img style='left:640px;display:none;' />").attr('src', imgSrc).load(function () {
$('#main-Image').attr('src', imgSrc);
$('#preview').css('background-image', 'none');
$('#main-Image').fadeIn();
});
return false;
});
});​
You can add all animations you want.
For a good slider, see http://bxslider.com/.