Fading blocks animation fullscreen - javascript

I'm trying to make a slider with fading blocks animation, just like here. Trouble is that in my case I'm trying to do it fullscreen, meaning that height and width will be variable. This means that the background-position trick won't work, as it won't resize the background to fit the screen but rather take it 'as is'. It's easier to see here (keep in mind that #slides would be height 100% and width 100% aswell as .slide>img). I've ran out of ideas to fix it, any help would be appreciated. I'd prefer not using jQuery, but if it is necessary, it'll be okay.
Thank you beforehand.
My script so far is:
function animateBlocks(x,y,speed) {
var width = document.getElementById('slides').offsetWidth;
var height = document.getElementById('slides').offsetHeight;
var newWidth = width/x;
var newHeight = height/y;
for (var i = 0; i<(x*y); i++) {
var newDiv = document.createElement("div");
document.getElementsByClassName('active-slide')[0].appendChild(newDiv);
newDiv.className = "slide-block";
newDiv.style.width = newWidth + 'px';
newDiv.style.height = newHeight + 'px';
newDiv.style.backgroundImage = 'url("' + document.getElementsByClassName('active-slide')[0].firstElementChild.src + '")';
newDiv.style.backgroundPosition = ('-' + newDiv.offsetLeft + 'px ' + '-' + newDiv.offsetTop + 'px');
if (i == x*y-1) {
document.getElementsByClassName('active-slide')[0].firstElementChild.style.display = 'none';
}
}
}

After the feedback of the comments, the issue may happen when there's float on window's width. So use document.documentElement.getBoundingClientRect(); to get a precise size, and round down, which may sacrifice some pixels, to ensure that blocks won't overflow to next row. jsfiddle
function animateBlocks(x,y,speed) {
var img = document.querySelector('#slides img');
var viewPortSize = document.documentElement.getBoundingClientRect();
// Round down if there's floating points on width.
var windowWidth = Math.floor(viewPortSize.width);
var windowHeight = window.innerHeight;
var newWidth = windowWidth / x;
var newHeight = windowHeight / y;
var newDiv;
var domFrag = document.createDocumentFragment();
var i, j;
for (i = 0; i < y; i +=1) {
for (j = 0; j < x; j += 1) {
newDiv = document.createElement("div");
domFrag.appendChild(newDiv);
newDiv.className = "slide-block";
newDiv.style.width = newWidth + 'px';
newDiv.style.height = newHeight + 'px';
newDiv.style.backgroundImage = 'url("' + document.getElementsByClassName('active-slide')[0].firstElementChild.src + '")';
newDiv.style.backgroundSize = windowWidth + 'px ' + windowHeight + 'px';
newDiv.style.backgroundPosition = ('-' + newWidth*j + 'px ' + '-' + newHeight*i + 'px');
}
}
for (var i = 0; i<(x*y); i++) {
}
document.getElementsByClassName('active-slide')[0].appendChild(domFrag);
document.getElementsByClassName('active-slide')[0].firstElementChild.style.display = 'none';
}
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden; /* makes the scroll bar disappear. */
}
#slides {
position: relative;
height: 100px;
margin: 0px;
padding: 0px;
}
.slide {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
display: none;
}
.slide>img {
position: absolute;
left: 0;
top: 0;
height: 100px;
}
.active-slide {
display: block;
}
.slide-block {
float: left;
}
<button onclick="animateBlocks(5,5,0)">Click here to see how it looks</button>
<ul id="slides">
<li class="slide active-slide">
<img src="http://www.planwallpaper.com/static/images/colorful-triangles-background_yB0qTG6.jpg">
</li>
</ul>
<br><br><br><br><br><br>
<p>How it should look</p>
<img style="height: 100px;" src="http://www.planwallpaper.com/static/images/colorful-triangles-background_yB0qTG6.jpg">

Related

Does not resize image

here is my URL
https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c
This image height and width is 225 & 400
i need height and width 100
here is javascript function
var myUrl = 'https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c';
var img = new Image();
img.src = myUrl;
var width;
var height;
img.addEventListener("load", function(){
console.log( this.naturalWidth +' '+ this.naturalHeight )
var imagewidth=this.naturalWidth;
var imageheight=this.naturalHeight;
var maxht =100;
var maxwt = 100;
if (imageheight > maxht || imagewidth > maxwt)
{
var old_ratio = imageheight / imagewidth;
var min_ratio = maxht / maxwt;
// If it can scale perfectly.
if (old_ratio === min_ratio) {
// this.resize_image(img, maxht, maxwt);
console.log(old_ratio);
console.log(min_ratio);
img.height = maxht;
img.width = maxwt;
console.log("does not change height and width");
console.log(img.src);
}
else {
var newdim = [imageheight, imagewidth];
newdim[0] = maxht; // Sort out the height first
// ratio = ht / wt => wt = ht / ratio.
var old_ratio = imageheight / imagewidth;
newdim[1] = newdim[0] / old_ratio;
// Do we still have to sort out the width?
if (newdim[1] > maxwt) {
newdim[1] = maxwt;
newdim[0] = newdim[1] * old_ratio;
}
//this.resize_image(img, newdim[0], newdim[1]);
img.height = newdim[0];
img.width = newdim[1];
console.log("change heigth and width");
console.log(img.src);
}
}
// width=this.naturalWidth;
// height=this.naturalHeight;
});
But does not change the height and width.
Kindly advice me,
Thanks
You can do this using only css properties.Below is a code sample.
Hope it will be useful
img {
max-width: 100px;
max-height: 100px;
}
<div>
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c">
<div>
You can just use CSS to resize your image, something like this:
img {
width: 100px;
height: 100px;
}
Always CSS first, if you couldn't solve it this way, then find a JavaScript way to solve it..
in JavaScript do it this way(as example), you can refine the code as suite you:
function resizeIMG(w, h){
var img = document.getElementsByTagName('img'), i=0;
while(img.length > i) {
img[i].style.width = w + 'px';
img[i].style.height = h + 'px';
i++;
}
}
and call it like this:
resizeIMG(100, 100);
function resizeIMG(w, h) {
var img = document.getElementsByTagName('img'),
i = 0;
while (img.length > i) {
img[i].style.width = w + 'px';
img[i].style.height = h + 'px';
i++;
}
}
resizeIMG(100, 100);
<div>
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c">
<div>
You can do this by writing this simple structure and css without stretching the image
.box {
width: 100px;
height: 100px;
overflow: hidden;
display: inline-block;
}
img {
max-width: 100%;
height: auto;
}
<div class="box">
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c" />
</div>
<div class="box">
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c">
</div>
<div class="box">
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c">
</div>
<div class="box">
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c">
</div>

Modifying CSS position with JS

I'm using document.getElementById("").style.top = var; to randomly change the position of an object every time I click on it, but I can only randomly change the position by pixels and not percentage. How do I randomly generate a number with % ?
document.getElementById("randObject").onclick = function () {
var bColor = "#"+((1<<24)*Math.random()|0).toString(16);
var yAxis = Math.random()*100;
var xAxis = Math.random()*100;
document.getElementById("randObject").style.backgroundColor = bColor;
document.getElementById("randObject").style.top = yAxis;
document.getElementById("randObject").style.left = xAxis;
}
document.getElementById("randObject").style.top = yAxis + "%";
document.getElementById("randObject").style.left = xAxis + "%";
I should point out that your color generator is also not valid 1/16 of the time. You need to left-zero-pad the string:
"#" + ("00000" + ((1<<24) * Math.random() | 0).toString(16)).slice(-6);
Another shortcut you can use to save DOM lookup time is to use the this keyword in your click event. All together it looks like:
Lastly, you might consider using .addEventListener('click', function() { ... }) since that is the current standard, though what you're doing works alright if you reeeally want to support IE6.
Let's check out the demo since this looks like a pretty neat script now:
document.getElementById("randObject").addEventListener('click', function() {
var bColor = "#" + ("00000" + ((1<<24) * Math.random() | 0).toString(16)).slice(-6);
var yAxis = Math.random() * 100;
var xAxis = Math.random() * 100;
this.style.backgroundColor = bColor;
this.style.top = yAxis + "%";
this.style.left = xAxis + "%";
});
:root {
/* change this value to update the size of playing field and #randObject */
--size: 50px;
}
html {
position: absolute;
margin: 0 var(--size) var(--size) 0;
padding: 0;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
body {
margin: 0;
padding: 0;
}
#randObject {
position: absolute;
top: 0;
left: 0;
width: var(--size);
height: var(--size);
background-color: #000000;
border-radius: 50%;
cursor: pointer;
transition-property: top, left, background-color;
transition-duration: 0.4s;
}
<div id="randObject"></div>
I added positioning to your code and I was able to make it to move by percentage.
<img id="randObject" width=100 height=100>
<script>
document.getElementById("randObject").onclick = function () {
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var bColor = "#"+((1<<24)*Math.random()|0).toString(16);
var yAxis = Math.random() + '%';
var xAxis = Math.random() + '%';
document.getElementById("randObject").style.backgroundColor = bColor;
document.getElementById("randObject").style.top = yAxis;
document.getElementById("randObject").style.left = xAxis;
document.getElementById("randObject").style.position = 'absolute';
}
</script>

How am I able to randomly set the position of the image in javascript

I am trying to make the smile.png image to appear in a random position within the specific <div>.
What I have done is to set the variable.style.top= top_position+'px' & variable.style.left = left_position+"px".
However, what I am getting so far are the images the are horizontally aligned and not randomly positioned. How am I able to do that?
var theLeftSide = document.getElementById("leftSide");
var randomY = Math.round(Math.random()) + 'px';
var randomX = Math.round(Math.random()) + 'px';
function generateFaces() {
for (numberOfFaces = 0; numberOfFaces < 5; numberOfFaces++) {
createElement(numberOfFaces);
}
}
number = 0;
function createElement() {
number++;
//creating the image on the leftside
var smiley = document.createElement('img');
smiley.src = "smile.png";
smiley.style.position = "absolute";
smiley.style.left = randomX;
smiley.style.top = randomY;
theLeftSide.appendChild(smiley);
}
#leftSide {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
position: absolute;
width: 500px;
height: 500px;
left: 500px;
border-left: 1px solid black;
}
<body id="smileyGuessingGame" onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
</body>
There are few syntax errors in your code. You can compare your code with the code provided below.
Also note toFixed returns a A string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place.
Try this:
var theLeftSide = document.getElementById("leftSide"),
top_position = parseInt(Math.random() * ($(document).width() - 500)),
left_position = parseInt(Math.random() * ($(document).width() - 500));
function generateFaces() {
for (var numberOfFaces = 0; numberOfFaces < 5; numberOfFaces++) {
createElement(numberOfFaces);
}
}
var number = 0;
function createElement() {
number++;
//creating the image on the leftside
var smiley = document.createElement('img');
smiley.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Smiley_head_happy.svg/2000px-Smiley_head_happy.svg.png";
smiley.style.position = 'absolute';
smiley.style.top = top_position + "px";
smiley.style.left = left_position + "px";
theLeftSide.appendChild(smiley);
top_position += 20;
left_position += 20;
}
#leftSide {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
position: absolute;
width: 500px;
height: 500px;
left: 500px;
border-left: 1px solid black;
}
img {
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body id="smileyGuessingGame" onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
</body>
Fiddle here
I'd code this using jQuery and lodash. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/3z6wsnyf/2/
The html:
<h1>Matching Game</h1>
<p>Find the unique image</p>
<div class="game"></div>
And the code:
var game = function(options) {
var panes = 2,
game = $('.game'),
height = 500,
width = game.width() / panes - 20,
itemSize = 50,
faces = 5,
guesses = 5,
setupBoard = function() {
game
.empty();
_.times(panes, function(p) {
game
.append(
$('<div>')
.addClass('pane pane' + p)
.css('height', height + 'px')
.css('width', width + 'px')
);
})
},
startGame = function() {
_.times(faces, function(i) {
_.times(panes, function(p) {
$('.pane' + p)
.append(
$('<img>')
.attr('src', 'http://lorempixel.com/200/20' + i)
.addClass('img-' + i)
.css('top', _.random(height - itemSize) + 'px')
.css('left', _.random(width - itemSize) + 'px')
);
})
});
$('.game img').click(function() {
guesses--;
alert('Nope! You\'ve got ' + guesses + ' guesses remaining.');
});
$('.pane' + _.random(panes - 1))
.append(
$('<img>')
.attr('src', 'http://lorempixel.com/200/20'+ (faces + 1))
.addClass('img-t')
.css('top', _.random(height - itemSize) + 'px')
.css('left', _.random(width - itemSize) + 'px')
.click(function() {
alert('You got it! Good job! You just cleared ' + faces + ' images! You\'ve got ' + guesses + ' guesses remaining.');
faces++;
setupBoard();
startGame();
})
);
$('.game img')
.css('height', itemSize + 'px')
.css('width', itemSize + 'px')
.css('-moz-border-radius', itemSize / 2 + 'px')
.css('-webkit-border-radius', itemSize / 2 + 'px')
.css('border-radius', itemSize / 2 + 'px')
.css('-khtml-border-radius', itemSize / 2 + 'px')
};
setupBoard();
startGame();
};
game();
Maybe something like this could work:
function generateRandom(min, max) {
var num = Math.random() * (max - min) + min;
return Math.floor(num);
}
var width,
height,
img;
width = $( '#leftSide' ).width();
height = $( '#leftSide' ).height();
img = $('<img id="smiley">');
img.attr('src', 'http://vignette2.wikia.nocookie.net/robocraft/images/2/26/Smile.png');
img.css('top',generateRandom(0,height));
img.css('left',generateRandom(0,width));
img.appendTo('#leftSide');
demo: http://codepen.io/anon/pen/PZZrzz

Same position and animation of dynamic generated Images

I have a few elements positioned in my HTML. The body has a max-width from 1280px with margin auto. And there are a few elements, which I floated right. In the middle of the page there should be 70 images go from left to right (and then dissapear). I have tried to make those elements position absolute with display: inline, but since the start and the end position should always be the same, and the images have a width and a height, I didn't know how to make it dynamically.. Thats my code so far:
HTML
<body>
<h1>Sweets</h1>
<div class="images"></div>
<div id="display"></div>
<div class="clear"></div>
<div id="maracons"></div>
<div id="cupCake"></div>
</body>
JQUERY
for (var i = 0; i < 10; i++) {
$('.images').append('<img class="image' + i.toString() + '" src="img/' + arr[i][5] + '">');
}
CSS
$leftPos: 1100px;
$widthImage: 200px;
.images{
width: $widthProducts;
height: 200px;
position: absolute;
left: 1100px;
top: 0px;
}
.image-1{
left: $leftPos;
}
.image-2{
left: $leftPos - $widthImage;
}
.image-3{
left: $leftPos - $widthImage*2;
}
Here is how it looks like:
Confusing question but from what I gather you want the images to have dynamic height/width when you are appending them? If so what do you want to make the width/height equal?
If thats the case here is the answer:
var imgWidth = 10, imgHeight = 10;
for (var i = 0; i < 10; i++) {
imgWidth = 100; //Set width
imgHeight = 100; //Set height
$('.images').append('<img style="width:' + imgWidth +'px!important; height:' + imgHeight + 'px !important; " class="image' + i.toString() + '" src="img/' + arr[i][5] +'">');
}
the !important keyword will force the width/height specified to ignore the width/height specified in the class..
sorry if this is not what you mean, a jsfiddle would be great.
UPDATE
Check this fiddle:
http://jsfiddle.net/xP8Qb/
Here is the kinda thing you were looking for:
$(document).ready(function () {
var endpoint = 800; //you can set left+top endpoints and ref them in loop below..
for (var i = 0; i < 3; i++) {
var html = '<div class="imgs img'+i+'"></div>';
setTimeout(function() {
$('.images').append(html);
$('.images>.imgs:last').animate({"left" : "300px"}, endpoint);
}, i * 1000);
}
});
i can work on it more if needed, but hopefully this is enough to put you on the right track..

How do I make text resizable to browser?

So I want to make the word "WIDTH" resize according to the width of the browser. Right now, only the box around the word resizes, but I want the word to resize as well. I feel like there's something wrong with my calculations.
<!DOCTYPE html>
<html>
<head>
<style>
#header{
margin: 0px;
font-size: 200px;
display:inline;
padding:0px;
position:absolute;
white-space:nowrap;
overflow:hidden;
border:thin solid black;
height:800px;
}
</style>
</head>
<body style="padding:0px;">
<div id="header"> WIDTH </div>
<script>
var text_div = document.getElementById("header");
var size = function (){
var winW = window.innerWidth;
var winH = window.innerHeight;
var win_ratio = winW/winH;
var offset_width = text_div.offsetParent.clientWidth;
var offset_height = text_div.clientHeight;
var offset_ratio = offset_width / offset_height;
text_div.style.width = offset_width + "px";
document.title = winW + ":" + offset_height;
text_div.style.fontSize=String(parseInt(winW/offset_ratio)) + "px";
}
window.onresize=function() {size();}
//size();
</script>
</body>
</html>
If you wrap your text in a span, you can get the text's offsetWidth
<div id="header"><span>WIDTH</span></div>
The div's width is fixed with left: 0px and right: 0px
#header {
position: absolute;
left: 0px;
right: 0px;
border: 1px solid black;
}
and the font-size is then adjusted dynamically. The for is there to prevent an endless loop
var epsilon = 5;
var div = document.getElementById('header');
var span = div.childNodes[0];
function size() {
var dw = div.offsetWidth;
var fs = 200;
span.style.fontSize = fs + 'px';
var cw = span.offsetWidth;
for (var i = 0; i < 10 && Math.abs(cw - dw) > epsilon; ++i) {
fs *= dw / cw;
span.style.fontSize = fs + 'px';
cw = span.offsetWidth;
}
}
window.onresize = size;
size();
JSFiddle
I'm not sure why you were using all the ratio stuff. Here's a simple example based on width alone.
http://jsfiddle.net/tHBpJ/3
var text_div = document.getElementById("header");
var initWinW = window.innerWidth;
var initFontSize = 40;
var size = function () {
var winW = window.innerWidth;
var textFactor = winW / initWinW
text_div.style.fontSize = initFontSize * textFactor + "px";
}
window.onresize = function () {
size();
}
I've used the jquery plugin fittext.js for this kind of thing in the past, and its worked quite nicely.

Categories

Resources