Image is not stopping after reaching max width of the screen - javascript

My question is: how do I stop the image from moving to the left when it reaches the user's maximum screen width? I tried the below method by using JavaScript but it is not working. Also when the image reaches the user's maximum width, it should change the direction and return to where it was before.
<img src="plane.jpg" width="100px" height="100px" id="plane">
<script type="text/javascript">
var height = document.documentElement.clientHeight;
var width = document.documentElement.clientWidth;
var plane = document.getElementById("plane");
var leftpos = 0;
setInterval(function(){
if (leftpos != width) {
leftpos += 10;
plane.style.marginLeft = leftpos + 'px'
}else {
// change the direction
}
}, 50) // run code every 50 milliseconds
;
</script>
Appreciate your time and Take care.

You can check if the marginLeft and the width of the image plus 10 is less than window.innerWidth.
var height = document.documentElement.clientHeight;
var width = window.innerWidth;
var plane = document.getElementById("plane");
var leftpos = 0;
var right = true;
var id = setInterval(function() {
if (right && leftpos + plane.width + 10 <= width) {
leftpos += 10;
} else {
right = false;
leftpos -= 10;
if (leftpos <= 0) clearInterval(id);
}
plane.style.marginLeft = leftpos + 'px';
}, 50);
<img src="plane.jpg" width="100px" height="100px" id="plane">

Related

Create divs in random places

I wish to create a div and position it in random places on the screen every 2 seconds. How would I accomplish this using PHP or Javascript? I am ok with using things like CSS.
div:
var blueMass = document.createElement('div');
blueMass.style.position = "absolute";
blueMass.innerHTML = "<img src='./pic/bluemass.png' height='35' width='35' />";
blueMass.id = "bluemass";
blueMass.className = "bluemass";
// my timer
window.setInterval(function(){
// Create the divs in here
}, 3000);
<div class="bluemass" id="bluemass">
<img src='./pic/bluemass.png' height='35' width='35' />
</div>
// no jQuery
$=document.querySelector.bind(document); // create selector
setInterval(function(){
s=$('div').style;
s.top=Math.random()*window.innerWidth+'px'; // multiply random (0..1) value by window height (you may want to subtract div height)
s.left=Math.random()*window.innerHeight+'px'; // ... height ...
},2000)
div{position:fixed}
<div>div</div>
// with jQuery
setInterval(function () {
$('#mydiv').css({
top: Math.random() * ($(window).height() - $('#mydiv').height()) + 'px', // multiply random .width(0..1) value by window height minus div height
left: Math.random() * ($(window).width() - $('#mydiv').width()) + 'px'
})
}, 2000)
#mydiv{position:fixed}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">div</div>
Just get width and height of document and use that to generate random number. You already have created the element in html, so no need to redo all that in JS.
In your specs you wanted every 2 seconds, so that would be 2000 ms in your timer.
In your timer function you would simply add the left and top of element with the new random numbers.
var blueMassElement = document.getElementById('bluemass');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
window.setInterval(function() {
// Create the divs in here
currentTop = Math.floor(Math.random() * documentHeight) + 1;
currentLeft = Math.floor(Math.random() * documentWidth) + 1;
blueMassElement.style.top = currentTop + "px";
blueMassElement.style.left = currentLeft + "px";
}, 2000);
#bluemass {
position:absolute;
}
<div id="bluemass" class="bluemass">
<img height="35" width="35" src='http://vignette4.wikia.nocookie.net/mrmen/images/5/52/Small.gif/revision/latest?cb=20100731114437' />
</div>

How to make script resize images and divs on window resize and orientation change

I am currently using the following javascript to resize an image to the size of it's parent, while maintaining aspect ratio and keeping the parent div square. So i have a square box with a rectangle stretched to either the max width or max height depending on orientation. This works great on first load however I cannot get the images and divs to resize on page orientation change or resize to work. Any ideas. I have tried using the window.resize and window.orientation listeners.
Original code was from:
Scale, crop, and center an image...
var aspHt = $('.aspectcorrect').outerWidth();
$('.aspectcorrect').css('height', aspHt + 'px').css('width', aspHt + 'px');
function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) {
var result = {
width : 0,
height : 0,
fScaleToTargetWidth : true
};
if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
return result;
}
// scale to the target width
var scaleX1 = targetwidth;
var scaleY1 = (srcheight * targetwidth) / srcwidth;
// scale to the target height
var scaleX2 = (srcwidth * targetheight) / srcheight;
var scaleY2 = targetheight;
// now figure out which one we should use
var fScaleOnWidth = (scaleX2 > targetwidth);
if (fScaleOnWidth) {
fScaleOnWidth = fLetterBox;
} else {
fScaleOnWidth = !fLetterBox;
}
if (fScaleOnWidth) {
result.width = Math.floor(scaleX1);
result.height = Math.floor(scaleY1);
result.fScaleToTargetWidth = true;
} else {
result.width = Math.floor(scaleX2);
result.height = Math.floor(scaleY2);
result.fScaleToTargetWidth = false;
}
result.targetleft = Math.floor((targetwidth - result.width) / 2);
result.targettop = Math.floor((targetheight - result.height) / 2);
return result;
}
function RememberOriginalSize(img) {
if (!img.originalsize) {
img.originalsize = {
width : img.width,
height : img.height
};
}
}
function FixImage(fLetterBox, div, img) {
RememberOriginalSize(img);
var targetwidth = $(div).width();
var targetheight = $(div).height();
var srcwidth = img.originalsize.width;
var srcheight = img.originalsize.height;
var result = ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox);
img.width = result.width;
img.height = result.height;
$(img).css("left", result.targetleft);
$(img).css("top", result.targettop);
}
function FixImages(fLetterBox) {
$("div.aspectcorrect").each(function(index, div) {
var img = $(this).find("img").get(0);
FixImage(fLetterBox, this, img);
});
}
window.onload = function() {
FixImages(true);
};
Call .resize() after $(window).resize():
$(window).resize( function(){
var height = $(window).height();
var width = $(window).width();
if(width>height) {
// Landscape
$("#landscape").css('display','none');
} else {
// Portrait
$("#landscape").css('display','block');
$("#landscape").click(function(){
$(this).hide();
});
}
}).resize();
I figured out what I was missing. The first bit of javascript is setting the style of height and width. When recalling the .outerHeight it was still using the inline style to calculate the width, and hence not resizing the div. I simply used .removeAttr('style') to remove that property first and then did the resize. Working now. I simply used $(window).on("resize", resizeDiv) and wrapped my resizing into a function named resizeDiv
function resizeDiv() {
var asp = $('.aspectcorrect');
asp.removeAttr("style");
var aspHt = asp.outerWidth();
asp.css('height', aspHt + 'px').css('width', aspHt + 'px');
FixImages(true);
}

How to display part of an image for the specific width and height?

Recently I participated in a web project which has a huge large of images to handle and display on web page, we know that the width and height of images end users uploaded cannot be control easily and then they are hard to display. At first, I attempted to zoom in/out the images to rearch an appropriate presentation, and I made it, but my boss is still not satisfied with my solution, the following is my way:
var autoResizeImage = function(maxWidth, maxHeight, objImg) {
var img = new Image();
img.src = objImg.src;
img.onload = function() {
var hRatio;
var wRatio;
var Ratio = 1;
var w = img.width;
var h = img.height;
wRatio = maxWidth / w;
hRatio = maxHeight / h;
if (maxWidth == 0 && maxHeight == 0) {
Ratio = 1;
} else if (maxWidth == 0) {
if (hRatio < 1) {
Ratio = hRatio;
}
} else if (maxHeight == 0) {
if (wRatio < 1) {
Ratio = wRatio;
}
} else if (wRatio < 1 || hRatio < 1) {
Ratio = (wRatio <= hRatio ? wRatio : hRatio);
}
if (Ratio < 1) {
w = w * Ratio;
h = h * Ratio;
}
w = w <= 0 ? 250 : w;
h = h <= 0 ? 370 : h;
objImg.height = h;
objImg.width = w;
};
};
This way is only intended to limit the max width and height for the image so that every image in album still has different width and height which are still very urgly.
And right at this minute, I know we can create a DIV and use the image as its background image, this way is too complicated and not direct I don't want to take. So I's wondering whether there is a better way to display images with the fixed width and height without presentation distortion?
Thanks.
I would recommend taking a look at something like twitter bootstraps carousel. In this they use an image tag within a div and size it by setting the image properties to something like
img {
height: auto;
max-width: 100%;
}
You can see a small example in this little fiddle.
By setting height to auto it will keep the ratio intact.
By setting max-width: 100% it will not zoom in the image past it's original size.
I solved this problem follow the following steps:
1, Write a method to zoom in/out the image to the appropriate width and height you want:
var autoResizeImage = function(targetWidth, targetHeight, objImg) {
if (0 >= targetWidth || 0 >= targetHeight) {
// Ilegal parameters, just return.
return;
}
var img = new Image();
img.src = objImg.src;
// Calculate the width and height immediately the image is loaded.
img.onload = function() {
var hRatio;
var wRatio;
var width = img.width;
var height = img.height;
var calcWidth = width;
var calcHeight = height;
wRatio = targetWidth / width;
hRatio = targetHeight / height;
if (wRatio < hRatio) {
calcWidth = targetWidth;
calcHeight = (targetHeight / height) * targetHeight;
} else {
calcHeight = targetHeight;
calcWidth = (targetWidth / width) * targetWidth;
}
objImg.width = calcWidth;
objImg.height = calcHeight;
};
};
and then call this method in its onload event like
<img src='PATH' onload='autoResizeImage(740, 460, this)'/>
2, Create a DIV outside of this image and style the width and height that you want to image displays with:
<div style='width: 740px; height: 460px; overflow:hidden;'></div>
And then the image would display with the fixed width and height you set.
Thanks for my friends from this site.

javascript toggle animation issue

I am doing a small javascript animation. this is my code :
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
heading.onclick = function () {
var divHeight = 250;
var speed = 10;
var myInterval = 0;
alert(divHeight);
slide();
function slide() {
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
alert('i am called as slide down')
}
}
function slideUp() {
var anima = document.getElementById('anima');
if (divHeight <= 0) {
divHeight = 0;
anima.style.height = '0px';
clearInterval(myInterval);
} else {
divHeight -= speed;
if (divHeight < 0) divHeight = 0;
anima.style.height = divHeight + 'px';
}
}
function slideDwn() {
var anima = document.getElementById('anima');
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
} else {
divHeight += speed;
anima.style.height = divHeight + 'px';
}
}
}
}
i am using above code for simple animation. i need to get the result 250 on the first click, as well second click i has to get 0 value. but it showing the 250 with unchanged. but i am assigning the value to set '0', once the div height reached to '0'.
what is the issue with my code? any one help me?
Everytime you click on the div the divHeight variable is reset to 250, thus your code never calls slideDwn. Moving the divHeight declaration outside the event handler should do the trick.
Also, your div wont have the correct size when any of the 2 animations end. You're setting the divHeight variable to 250 or 0 correctly, but never actually setting anima.style.height after that.
I've rewritten your code into something simpler and lighter. The main difference here is that we're using a single slide() function here, and that the height of the div in question is stored in a variable beforehand to ensure that the element slides into the correct position.
Note that this is a very simplistic implementation and assumes that the div carries no padding. (The code uses ele.clientHeight and ele.style.height interchangeably, which admittedly, is a pretty bad choice, but is done here to keep the code simple)
var heading = document.getElementsByTagName('h1')[0],
anima = document.getElementById('anima'),
divHeight = anima.clientHeight,
speed = 10,
myInterval = 0,
animating = false;
function slide(speed, goal) {
if(Math.abs(anima.clientHeight - goal) <= speed){
anima.style.height = goal + 'px';
animating = false;
clearInterval(myInterval);
} else if(anima.clientHeight - goal > 0){
anima.style.height = (anima.clientHeight - speed) + 'px';
} else {
anima.style.height = (anima.clientHeight + speed) + 'px';
}
}
heading.onclick = function() {
if(!animating) {
animating = true;
var goal = (anima.clientHeight >= divHeight) ? 0 : divHeight;
myInterval = setInterval(slide, 13, speed, goal);
}
}
See http://www.jsfiddle.net/yijiang/dWJgG/2/ for a simple demo.
I've corrected your code a bit (See working demo)
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
var anima = document.getElementById('anima');
var divHeight = 250;
heading.onclick = function () {
var speed = 10;
var myInterval = 0;
function slideUp() {
divHeight -= speed;
if (divHeight <= 0) {
divHeight = 0;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slideDwn() {
divHeight += speed;
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slide() {
console.log(divHeight )
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
}
}
slide();
}
}​

How do i get relative dimensions of scrollbale window viewport

I am having a Tooltip (larger image view) that is being positioned via e.pageX e.pageY and i am trying to make sure it is not hidden below the current scrolled view port.
I have seen many sites have this
my code is something like this but i am missing something.
var positionImg = function(e) {
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
var mouseAtY = e.pageY;
var mouseAtX = e.pageX;
var maxBottomVPos = viewportHeight-"i dont know";
var maxTopVPos = 30;
if (mouseAtY >= maxBottomVPos)
{
tPosX = mouseAtX+ 10;
tPosY = mouseAtY -520;
}
else if (mouseAtY <= maxTopVPos)
{
tPosX = mouseAtX;
tPosY = mouseAtY +40;
}
else
{
tPosX = mouseAtX;
tPosY = mouseAtY +20;
}
$zoomContainer.css({top: tPosY, left: tPosX});
};
var maxBottomVPos = viewportHeight-"i dont know";
You probably don't want to go any lower than the height of the element that you are positioning. So use the height of zoomContainer to figure out how much higher it needs to go. This way, the whole thing can be included. Of course, you'll have to consider that the user might shrink the screen too small to fit the container.
To get the scroll offset use scrollTop. With this you will have both the size of the viewport and how far down the viewport is.
I found the answer:
Quite simple:
var positionImg = function(e) {
cntnrH = $zoomContainer.height() + 230;
calHight = e.pageY - $(window).scrollTop() + cntnrH;
docH = $(window).height()
var mouseAtY = e.pageY;
var mouseAtX = e.pageX;
if (calHight >= docH)
{
tPosX = mouseAtX + 5;
tPosY = mouseAtY - cntnrH;
}
else if (calHight <= calHight){
tPosX = mouseAtX;
tPosY = mouseAtY + 15;
}
else
{
tPosX = mouseAtX;
tPosY = mouseAtY +20;
}
$zoomContainer.css({top: tPosY, left: tPosX});
};
doIt = $("img.hovelble");
doIt.hover(showZoomImg, hideZoomImg).mousemove(positionImg);
});

Categories