How to add percentages in Javascript - javascript

I'm trying to make a slider by adding 100% to each image but can not get it done.
My main question is how to add the percentages. I tried console.log(100% + 100%) just for an example and it does not work either. Thanks for any suggestions.
<section class="slider">
<img class="img" id="img1" src="girl.jpg" alt="" style="left: -100%">
<img class="img" id="img2" src="sport.jpg" alt="" style="left: 200%" >
<img class="img" id="img3" src="biceps.jpg" alt="" style="left: 100%" >
<img class="img" id="img4" src="weights.jpg" alt="" style="left: 0%">
</section>
javascript
var img = document.getElementsByClassName('img');
function slide() {
for(i=0; i < img.length; i++) {
img[i].style.left += "100%";
console.log(img[i].style.left);
}
}

You can't because this attribute's value is not a number (it's a text). So here's what you can do:
Try to parse the text to get only the number portion, parse it into an integer, do the math, then turn it back to a string. Something like
let tempPercent = parseInt(img[i].style.left.replace('%', ''), 10);
tempPercent += 100;
img[i].style.left = tempPercent+'%';

Related

Show next image on top of the current image with JavaScript/jQuery

I have a series of images with the class of .piece in a div called #pieces. Only the first image #piece0 is shown initially, and as you click on #piece0, #piece1 appears on top of #piece0. And then when you click on #piece1, #piece2 appears on top. My current code doesn't do that. How do I fix that?
<div id="pieces">
<img class="piece" id="piece0" style="display:block;"/>
<img class="piece" id="piece1" style="display:none;"/>
<img class="piece" id="piece2" style="display:none;"/>
<img class="piece" id="piece3" style="display:none;"/>
</div>
<script>
var pieceNum = $("#pieces").children().size();
var i = 0;
if (i < pieceNum) {
$("#piece" + i).click(function({
i++;
$("piece" + i).css("display", "block");
}));
}
</script>
If you want to get element children size(length) , use $("#pieces img").length . But for your problem that is not necessary .
You can catch image click by $("pieces img").on("click".. and get next element by .next() then the last element have no next , for that case you can check by next().length . 0 will return if next element have no exist
$("#pieces img").on("click",function() {
$(this).next().show();
$("#pieces").append($(this));
});
#pieces {
display: flex;
flex-direction: column;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pieces">
<img class="piece" id="piece0" style="display:block;" alt="one"/>
<img class="piece" id="piece1" style="display:none;" alt="two"/>
<img class="piece" id="piece2" style="display:none;" alt="three"/>
<img class="piece" id="piece3" style="display:none;" alt="four"/>
</div>
$(document).ready(function(){
var pieceNum = $("#pieces").children();
var i = 0;
if (i < pieceNum.length) {
$("#piece" + i).click(function(){
$("#piece" + i).css("display", "none");
i++;
$("#piece" + i).css("display", "block");
});
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pieces">
<img class="piece" id="piece0" style="display:block;" src="http://placekitten.com/g/200/300"/>
<img class="piece" id="piece1" style="display:none;" src="http://placekitten.com/g/200/400"/>
<img class="piece" id="piece2" style="display:none;" src="http://placekitten.com/g/200/300"/>
<img class="piece" id="piece3" style="display:none;" src="http://placekitten.com/g/200/100"/>
</div>
Try this:
var pieceNum = $("#pieces").children().size();
var i = 0;
if (i < pieceNum) {
$("#piece" + i).click(function({
$("piece" + i).css("display", "none");
i++;
$("piece" + i).css("display", "block");
}));
}
You don't need to write multiple click events, You can have single click event attached to all elements and do traversing using .next() to show next element :
$(".piece").click(function({
var $nextPiece = $(this).next();
if($nextPiece.length > 0)
$nextPiece.css("display", "block");
}));
You can use the next() to access next child and show() to display the img. Also, you will need to add position: absolute; to make images overlap each other.
$(document).ready(function() {
$('.piece').on('click', function() {
$(this).next().show();
});
});
img {
max-width: 100px;
margin-right: 1em;
position: absolute;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div id="pieces">
<img class="piece" src="https://res.cloudinary.com/demo/image/upload/w_250,h_250,c_mfit/w_700/sample.jpg" />
<img class="piece" src="https://res.cloudinary.com/demo/image/upload/w_300,h_200,c_crop/sample.jpg" style="display:none;" />
<img class="piece" src="https://res.cloudinary.com/demo/image/upload/w_250,h_250,c_mfit/w_700/sample.jpg" style="display:none;" />
<img class="piece" src="https://res.cloudinary.com/demo/image/upload/w_300,h_200,c_crop/sample.jpg" style="display:none;" />
</div>
Try this
$(".piece").on('click', function(){
$(".piece").hide();
let id = (parseInt(this.id.slice(-1)) +1)%4;
$("#piece" +id).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pieces">
<img class="piece" id="piece0" style="display:block;" alt="piece 0"/>
<img class="piece" id="piece1" style="display:none;" alt="piece 1"/>
<img class="piece" id="piece2" style="display:none;" alt="piece 2"/>
<img class="piece" id="piece3" style="display:none;" alt="piece 3"/>
</div>

Set same height for all images

I have three images and I am displaying them one by one, they have different height and that push and pull other content based on image height. When I set fixed height for image, the height will not be responsive anymore. How to set same height for these images where responsive can still work?
This is my Script:
var i = 0; var path = new Array();
path[0] = "/pic/Company.png";
path[1] = "/pic/S031.png";
path[2] = "/pic/AnnualReport2015_f.png";
function swapImage() {
document.slide.src = path[i];
if (i < path.length - 1) i++;
else i = 0;
setTimeout("swapImage()", 3000);
}
CSS but it does not solve my problem :
#left-img
{
max-height: 500px;
}
HTML:
<div class="col-md-8">
<img name="slide" src="home1.jpg" class="img-responsive" id="left-img"/>
</div>
Use their class instead of their id, and btw, id should be unique for every image
With max-height: 300px, only bigger gets resized down to 300px, using height: 300px will do the same but also up size smaller (and all will keep their aspect ratio).
.img-responsive
{
height: 300px;
}
<div class="col-md-8">
<img name="slide" src="http://placehold.it/150x200" class="img-responsive" id="left-img-1"/>
<img name="slide" src="http://placehold.it/150x300" class="img-responsive" id="left-img-2"/>
<img name="slide" src="http://placehold.it/150x400" class="img-responsive" id="left-img-3"/>
<img name="slide" src="http://placehold.it/150x500" class="img-responsive" id="left-img-4"/>
</div>

Multiple Auto fade in/fade out on loop in multiple divs

I have 3 columns in a table with different pictures in each. I am trying to have the fade at different times with different pictures in a loop and to start automatically.
I have managed to get it working but i have after about 20 seconds i have white boxes and not images.
Here is a link to it on https://jsfiddle.net/nmcj4yze/3/.
My Jquery code:
$(document).ready(function () {
var InfiniteRotator = {
init: function () {
//initial fade-in time (in milliseconds)
var initialFadeIn = 4000;
//interval between items (in milliseconds)
var itemInterval = 4000;
//cross-fade time (in milliseconds)
var fadeTime = 4000;
//count number of items
var numberOfItems = $('.rotating-home').length;
//set current item
var currentItem = 0;
//show first item
$('.rotating-home').eq(currentItem).fadeIn(initialFadeIn);
//loop through the items
var infiniteLoop = setInterval(function () {
$('.rotating-home').eq(currentItem).fadeOut(fadeTime);
var rand = Math.floor(Math.random() * (numberOfItems - 1)) + 1;
currentItem = (currentItem + rand) % numberOfItems;
$('.rotating-home').eq(currentItem).fadeIn(fadeTime);
}, itemInterval);
}
};
InfiniteRotator.init();
});
//]]>
Css:
body {
color:#999;
font-family:"MS Serif", "New York", serif;
font-size:16px;
padding-left:20px;}
/* slider */
#rotating-item-wrapper {
list-style-type:none;
margin:0;
padding:0;
height: 150px;
}
.rotating-home {
display:;
position: absolute;
}
And Html:
<table width="60%" align="center">
<tr>
<td>
<div id="rotating-home-wrapper">
<div class="rotating-home">
<img src="http://paul.cerrone.me/wp-content/uploads/2013/06/BQcDAAAAAwoDanBnAAAABC5vdXQKFjlCVTZ6M0RDM3hHN2xTbFRpWUlPQlEAAAACaWQKAXgAAAAEc2l6ZQ.jpg" height="100" width="100" border="0" />
</div>
<div class="rotating-home">
<img src="http://www.dailyfailcenter.com/sites/default/files/fail/ea662e71d267.jpg" class="slide" height="100" width="100" border="0" />
</div>
</td>
<td>
<div class="rotating-home">
<img src="http://blog.epromos.com/images/google-dog.jpg" class="slide" height="100" border="0" />
</div>
<div class="rotating-home">
<img src="http://www.thelastnewspaper.com/images-future/gps-dog-tracking-300x400.jpg" class="slide" height="100" border="0" />
</div>
</td>
<td>
<div class="rotating-home">
<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQHzIZUSCKJBajh8kY8zbVmyYYBCbzgy7ADISw6h9cCJ-Mw2pwnFw" class="slide" height="100" border="0" />
</div>
<div class="rotating-home">
<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSWgFW9ZbKPn3_ECEJgV58atYzlbyZzKzvkhgsP3zdt4BFmw_7GfQ" class="slide" height="100" border="0" />
</div>
</td>
</div>
</tr>
Updated
Sorry i should of been more clear.
At first i want 3 columns in a table. The first one was 600x600, the second was 300x600 and the third was 300x600. When the page loads you see 3 pictures. After 4 seconds column 1 fades into another picture without going to a white background. After another 4 seconds column two fades into a another picture, and after another 4 seconds column 3 does then same. I would like to be on a continuous cycle so it would start again. But i couldn't do that, i did achieve something close with a random cycle but i have white backgrounds after about 20 seconds. Not sure where i am going wrong
I have tried everything and and look everywhere.
Any help will be much appreciated.
Thanks
I'm assuming the following is what you wanted:
https://jsfiddle.net/nmcj4yze/7/
You were on the right track. I cleaned up your HTML a bit, and removed some CSS that wasn't doing anything. I also made it so that the initial image in each table was hidden.
With regards to the javascript, I switched out the selectors to iterate over each <td> element, and had it use jQuery's fadeToggle() function on its contents. Given that the first item was hidden by default, this would immediately toggle the animations for both images.
Changed your code to the following:
$(document).ready(function () {
var InfiniteRotator = {
init: function () {
//initial fade-in time (in milliseconds)
var initialFadeIn = 4000;
//interval between items (in milliseconds)
var itemInterval = 4000;
//cross-fade time (in milliseconds)
var fadeTime = 4000;
//count number of items
var rotationLimit = $('td').length + 1;
//set current item
var currentItem = 0;
//loop through the items
var infiniteLoop = setInterval(function () {
$('td').eq(currentItem).find('.rotating-home').fadeToggle(fadeTime);
currentItem++;
if(currentItem == rotationLimit) currentItem = 0;
}, itemInterval);
}
};
InfiniteRotator.init();
});
//]]>
#charset"utf-8";
#page {
height: 100%;
display: none;
}
body {
color:#999;
font-family:"MS Serif", "New York", serif;
font-size:16px;
padding-left:20px;
}
.rotating-home {
position: absolute;
}
.rotating-home:first-of-type {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table width="60%" align="center">
<tr>
<td>
<div class="rotating-home" data-display="0">
<img src="http://paul.cerrone.me/wp-content/uploads/2013/06/BQcDAAAAAwoDanBnAAAABC5vdXQKFjlCVTZ6M0RDM3hHN2xTbFRpWUlPQlEAAAACaWQKAXgAAAAEc2l6ZQ.jpg" height="100" width="100" border="0" />
</div>
<div class="rotating-home" data-display="1">
<img src="http://www.dailyfailcenter.com/sites/default/files/fail/ea662e71d267.jpg" class="slide" height="100" width="100" border="0" />
</div>
</td>
<td>
<div class="rotating-home" data-display="2">
<img src="http://blog.epromos.com/images/google-dog.jpg" class="slide" height="100" border="0" />
</div>
<div class="rotating-home" data-display="3">
<img src="http://www.thelastnewspaper.com/images-future/gps-dog-tracking-300x400.jpg" class="slide" height="100" border="0" />
</div>
</td>
<td>
<div class="rotating-home" data-display="4">
<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQHzIZUSCKJBajh8kY8zbVmyYYBCbzgy7ADISw6h9cCJ-Mw2pwnFw" class="slide" height="100" border="0" />
</div>
<div class="rotating-home" data-display="5">
<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSWgFW9ZbKPn3_ECEJgV58atYzlbyZzKzvkhgsP3zdt4BFmw_7GfQ" class="slide" height="100" border="0" />
</div>
</td>
</tr>
</table>

Display more than one image at onmouseover event

I have the following code which displays an image onmouseover and sets back the default image active onmouseout.
<img src="image1.jpg" onmouseover="this.src='image2.jp'" onmouseout="this.src='image1.jpg'" />
I want to be able to display multiple images onmouseover event; each displaying after a set time. Can anyone help me out on this?
HTML
<div id="container">
<img id="initialIMG" src="http://icons.iconarchive.com/icons/jamespeng/construction/128/bonecrusher-icon.png" />
</div>
<img src="http://icons.iconarchive.com/icons/jamespeng/construction/128/bonecrusher-icon.png" onmouseover="this.src='http://icons.iconarchive.com/icons/jamespeng/construction/128/longhaul-icon.png'" onmouseout="this.src='http://icons.iconarchive.com/icons/jamespeng/construction/128/bonecrusher-icon.png'" />
JavaScript
$(document).ready(function(){
$("#container").mouseenter(function() {
var t = setTimeout(function(){
$("#initialIMG").hide();
$("#initialIMG").attr("src", "http://icons.iconarchive.com/icons/jamespeng/construction/128/longhaul-icon.png" )
$("#initialIMG").fadeIn(50);
$("#container").append( '<img id="addedIMG" src="http://icons.iconarchive.com/icons/jamespeng/construction/128/mixmaster-icon.png" style="display:none;"/>' );
$("#addedIMG").fadeIn(50);
},500);
});
$("#container").mouseleave(function() {
var t = setTimeout(function(){
$("#initialIMG").hide();
$("#initialIMG").attr("src", "http://icons.iconarchive.com/icons/jamespeng/construction/128/bonecrusher-icon.png" )
$("#initialIMG").fadeIn(50);
$("#addedIMG").remove();
},500);
});
});
FIDDLE
Try this:
function showImage() {
//Your code here
}
function hideImage() {
//Your code here
}
<img src="image1.jpg" onmouseover="showImage();" onmouseout="hideImage();" />
Is there any specific reason you don't want to use jQuery?
in css:
#my-pics .default{
display: inline;
}
in html:
<div id="my-pics">
<img src="image1.jpg" class="default" />
<img src="image2.jpg" style="display:none;" />
<img src="image3.jpg" style="display:none;" />
</div>
in js:
$("#my-pics").mouseenter(function(){
$(this).find(".default").hide();
$(this).find(":not(.default)").show();
}).mouseleave(function(){
$(this).find(".default").show();
$(this).find(":not(.default)").hide();
});
Of course you need to import jquery first. Haven't tested this myself, any errors?
CSS solution?
in html:
<div id="my-pics">
<img src="image1.jpg" class="default" />
<img src="image2.jpg"/>
<img src="image3.jpg"/>
</div>
in css:
#my-pics img{
display: none;
}
#my-pics img.default{
display: inline;
}
#my-pics:hover img{
display: inline;
}
#my-pics:hover img.default{
display: none;
}
A quick solution, maybe not the most beautiful one, but it works.
HTML:
<img id="image1" src="image1.jpg" onmouseover="showImages()" onmouseout="hideImages()" />
<img id="image2" src="image2.jpg" style="display:none;" />
<img id="image3" src="image3.jpg" style="display:none;" />
Javascript:
function showImages(){
document.getElementById('image2').style = '';
document.getElementById('image3').style = '';
}
function hideImages(){
document.getElementById('image2').style = 'display: none;';
document.getElementById('image3').style = 'display: none;';
}
Of course you should solve this with classes to clean up your code. This is just a basic example that works.
If you are using jQuery then when your document is ready:
<img class="main-image" data-target=".images-set1" src="mainImage1.jpg">
secondary images:
<div class="images-set1">
<img src="secondary1-1.jpg" style="display:none">
<img src="secondary1-2.jpg" style="display:none">
<img src="secondary1-2.jpg" style="display:none">
....
</div>
with jQuery:
$('main-image').on('mouseover', function (event) {
$($(event.target).attr('data-target') + ' img').show();
})
.on('mouseout', function (event) {
$($(event.target).attr('data-target') + ' img').hide();
});
this will just hide/show the secondary image element related to the main image,
tell me if this is not exactly the behaviour you want.

Clicking on thumbnail changes an unintended main image

When I click on a thumbnail meant to change (img), it changes the main image of (img1) as well.
I would want only AGM thumbnails to change (img), and BLACSBF to change (img1)
Would appreciate any assistance. (:
My Javascript
function changeImage(img) {
document.getElementById("img").src = img.src.replace("_t", "_b");
document.getElementById("img1").src = img.src.replace("_t", "_b");
My HTML
<img src="images/AGM/events_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/AGM/events1_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/BLACSBF/events1_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img1" src="images/BLACSBF/events_b.jpg" width="650">
Thank you very much!
You need to pass the targeted image element as a parameter to the changeImage function
function changeImage(img, target) {
document.getElementById(target).src = img.src.replace("_t", "_b");
}
then
<img src="images/AGM/events_t.jpg"
onclick="changeImage(this, 'img');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/AGM/events1_t.jpg"
onclick="changeImage(this, 'img');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg"
onclick="changeImage(this, 'img1');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/BLACSBF/events1_t.jpg"
onclick="changeImage(this, 'img1');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img1" src="images/BLACSBF/events_b.jpg" width="650">
You might be able to simplify your markup a little more if you attached event handlers directly in JavaScript. This isn't a cross browser method, but it certainly does work. Firstly you could slim down your markup and turn the bigger img elements into classes, instead of having a bunch of unique IDs to worry about:
<img src="images/AGM/events_t.jpg">
<img src="images/AGM/events1_t.jpg">
<img class="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg">
<img src="images/BLACSBF/events1_t.jpg">
<img class="img" src="images/BLACSBF/events_b.jpg" width="650">
Then, in your JavaScript, you could cycle through all the img tags that don't have a class attribute, and add your event handlers with addEventListener() ( this is the part that will not work on IE8, but can be easily fixed with a cross browser implementation).
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
if (!imgs[i].getAttribute('class')) {
//mouseout handler
imgs[i].addEventListener("mouseout", function () {
this.style.opacity = 1;
this.filters.alpha.opacity = 100;
});
//mouseover handler
imgs[i].addEventListener("mouseover", function () {
this.style.opacity = 0.5;
this.filters.alpha.opacity = 0.5;
});
//click handler
imgs[i].addEventListener("click", function () {
var src = this.src.replace("_t", "_b");
var fullImg = siblingByClass(this);
fullImg.src = src;
//traverse siblings till 'img' class is found
function siblingByClass(node) {
var sibling = node.nextSibling;
if (sibling.nodeType === 3 || sibling.getAttribute('class') !== 'img') {
return siblingByClass(sibling);
} else {
return sibling;
}
}
});
}
}
jsFiddle

Categories