centering the full page background image in javascript - javascript

I am using the code from this link http://css-tricks.com/perfect-full-page-background-image/
<script>
$(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
$bg.style.marginTop = (-theWindow.height() / 2) + 'px';
       $bg.style.marginLeft = (-theWindow.width() / 2) + 'px';
}
theWindow.resize(function() {
resizeBg();
}).trigger("resize");
});
</script>
<style>
#bg { position: fixed; top: 0; left: 0; z-index:-2;}
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
</style>
<body>
<div id="caseStudies">
<img src="images/caseStudy01.jpg" alt="Case Study 1" id="bg">
</div>
</body>
but I want to center the background image. I have tried to this by using the following code:
$bg.style.marginTop = (-theWindow.height() / 2) + 'px';
$bg.style.marginLeft = (-theWindow.width() / 2) + 'px';
which isn't working. Am I referencing the correct values?

I think you should try with this:
$bg.style.marginTop = ($bg.height()/2-theWindow.height() / 2) + 'px';
$bg.style.marginLeft = ($bg.width()/2-theWindow.width() / 2) + 'px';

Related

change background position with skrollr.js

i want to change the background position on scroll with skrollr.js library , my background image has lots of images ( about 500 images ) and i want to change theme on scrolling , how can i do it ?
i want to do something like this code but with skrollr.js library :
$(function() {
var rotator = $('#rotator');
var container = $(document);
var viewport = $(window);
var images = 72;
var imageHeight = 30000 / images;
var scrollHeight = container.height() - viewport.height() + imageHeight;
var step = images / scrollHeight;
viewport.scroll(function(event) {
var x = -Math.floor(step * viewport.scrollTop()) * imageHeight;
rotator.css('background-position', x + 'px 0');
});
});
body {
height: 2000px;
}
#rotator {
font-size: 416px;
width: 1em;
height: 1em;
position: fixed;
top: 0;
right: 0;
z-index: -1;
background: transparent url(http://www.3sessanta.it/images/polaroid/sprite_polaroid_total.jpg) no-repeat 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rotator"></div>
Example Demo

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>

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

Fading blocks animation fullscreen

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">

Saving position for div after dragging

I have the following script, when dragging the gray handler (top left) div re-sizes but at release of the mouse div is being place in the wrong place (at left margin).
I need to fix it as would be the bottom right handler.
What could be the problem? It seems related with event.clientX which is set to 0.
NOTES: click on the div to activate the handlers.
http://jsfiddle.net/cx41otxp/
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#target {
background-color: lightgreen;
}
.selected {
border: 1px dashed red;
}
.handler {
position: absolute;
width: 10px;
height: 10px;
background-color: gray;
}
</style>
<script>
window.App = {
config: {
elm: 'target',
elmInnerContent: 'inner-content',
x: null,
y: null,
w: null,
h: null,
handlerSize: 10
},
start: function () {
this.addEventListeners();
},
addEventListeners: function () {
var elm = document.getElementById(this.config.elm);
elm.addEventListener('click', function () {
if (!elm.classList.contains('selected')) {
elm.classList.add('selected');
this.getDimensions();
this.createHandlers();
this.setPositionHandlers();
this.addEventListenersHandlers();
} else {
elm.classList.remove('selected');
this.removeHandlers();
}
}.bind(this));
},
removeHandlers: function () {
var elm = document.getElementById('handler-wrapper');
elm.parentElement.removeChild(elm);
},
getDimensions: function () {
var elm = document.getElementById(this.config.elm);
this.config.x = elm.offsetLeft;
this.config.y = elm.offsetTop;
this.config.w = elm.clientWidth;
this.config.h = elm.clientHeight;
},
createHandlers: function () {
var wrpHandlers = document.createElement('div'),
htmlHandlers = '<div id="tl" class="tl handler" draggable="true"> </div>';
htmlHandlers += '<div id="tr" class="tr handler" draggable="true"> </div>';
htmlHandlers += '<div id="bl" class="bl handler" draggable="true"> </div>';
htmlHandlers += '<div id="br" class="br handler" draggable="true"> </div>';
wrpHandlers.id = "handler-wrapper";
wrpHandlers.innerHTML = htmlHandlers;
var elm = document.getElementById(this.config.elm);
elm.appendChild(wrpHandlers);
},
setPositionHandlers: function () {
this.getDimensions();
var elmTl = document.getElementById('tl'),
elmTr = document.getElementById('tr'),
elmBl = document.getElementById('bl'),
elmBr = document.getElementById('br');
elmTl.style.top = this.config.handlerSize * -1 + 'px';
elmTl.style.left = this.config.handlerSize * -1 + 'px';
elmTr.style.top = this.config.handlerSize * -1 + 'px';
elmTr.style.left = this.config.w + 'px';
elmBl.style.top = this.config.h + 'px';
elmBl.style.left = this.config.handlerSize * -1 + 'px';
elmBr.style.top = this.config.h + 'px';
elmBr.style.left = this.config.w + 'px';
},
addEventListenersHandlers: function () {
var elmTl = document.getElementById('tl'),
elmTr = document.getElementById('tr'),
elmBl = document.getElementById('bl'),
elmBr = document.getElementById('br');
elmTl.addEventListener('drag', function (event) {
this.resize('tl', event);
}.bind(this));
elmTr.addEventListener('drag', function (event) {
this.resize('tr', event);
}.bind(this));
elmBl.addEventListener('drag', function (event) {
this.resize('bl', event);
}.bind(this));
elmBr.addEventListener('drag', function (event) {
this.resize('br', event);
}.bind(this));
},
resize: function (handler, event) {
var elm = document.getElementById(this.config.elm);
switch (handler) {
case 'tl':
var marginR = elm.offsetLeft + elm.clientWidth,
newW = marginR - event.clientX,
xPos = event.clientX;
elm.style.left = xPos + 'px';
elm.style.width = newW + 'px';
this.setPositionHandlers();
break;
case 'tr':
break;
case 'bl':
break;
case 'br':
var newW = event.clientX - this.config.x,
newH = event.clientY - this.config.y;
elm.style.width = newW + 'px';
elm.style.height = newH + 'px';
this.setPositionHandlers();
break;
}
},
};
</script>
<title></title>
</head>
<body onload="window.App.start();">
<div id="target" style="position: absolute; top: 100px; left: 100px; width: 100px; height: 100px;">
<div id="inner-content">
Some text here
</div>
</div>
</body>
</html>
In the resize function, case 'tl': you have to do the same thing for top & height, what you do for left & width.
marginT = elm.offsetTop + elm.clientHeight,
newH = marginT - event.clientY,
yPos = event.clientY;
and
elm.style.top = yPos + 'px';
elm.style.height = newH + 'px';
Edit: Sorry, I think misread something the first time.
FYI: your code is working fine in Safari, but in Chrome, I see your problem.
Edit2: I don't know what causes this. But if you just check xPos >= 0, you can work around it. I know it's an ugly hack, but this is the best I have. Fiddle updated.

Categories

Resources