Javascript-moving image - javascript

How is it posible move an image from one position to other with fadeout?
I hav such functions
for hiding:
function SetOpacity(object,opacityPct)
{
// IE.
object.style.filter = 'alpha(opacity=' + opacityPct + ')';
// Old mozilla and firefox
object.style.MozOpacity = opacityPct/100;
// Everything else.
object.style.opacity = opacityPct/100;
}
function ChangeOpacity(id,msDuration,msStart,fromO,toO)
{
var element=document.getElementById(id);
var opacity = element.style.opacity * 100;
var msNow = (new Date()).getTime();
opacity = fromO + (toO - fromO) * (msNow - msStart) / msDuration;
if (opacity<0)
SetOpacity(element,0)
else if (opacity>100)
SetOpacity(element,100)
else
{
SetOpacity(element,opacity);
element.timer = window.setTimeout("ChangeOpacity('" + id + "'," + msDuration + "," + msStart + "," + fromO + "," + toO + ")",1);
}
}
function FadeOut(id)
{
var element=document.getElementById(id);
if (element.timer) window.clearTimeout(element.timer);
var startMS = (new Date()).getTime();
element.timer = window.setTimeout("ChangeOpacity('" + id + "',500," + startMS + ",100,0)",1);
}
for get current position or next position (by id of image and id of div)
function findPos(e){
var obj = document.getElementById(e);
var posX = obj.offsetLeft;var posY = obj.offsetTop;
while(obj.offsetParent){
posX=posX+obj.offsetParent.offsetLeft;
posY=posY+obj.offsetParent.offsetTop;
if(obj==document.getElementsByTagName('body')[0]){break}
else{obj=obj.offsetParent;}
}
alert(posX+'-'+posY);
}
the first position is position of image, and next - is position of div

The easiest approach with minimal code will be to use jQuery and use the animate function mate.
Ex:
$(".block").animate({"left": "+=50px"}, "slow");
You can use multiple parameters in the brackets like background-color, opacity, etc as you wish to dynamically change the values.
A link for your reference is located at: http://api.jquery.com/animate/

Most javascript animations rely on timer to create the effect of fluid motion. To slide an image across the page, you would set an interval that changed the css position to the right 1px every 5 milliseconds or something of the like. Javascript animation tutorial.
However, animation is most easily accomplished with a library like jquery or many others.

Related

How we can move CSS object from Right to Left using javascript?

Hi, In javascript we have option of finding offSetRight position of Element and can move it towards Left to Right side using setInterval method but i like to bring that object from right to left and i did not find any javascript method which i can use Here in my code , if you guys can take a look it would be great, also i like to mention i am new to Js so i hope people will go easy on me.
P.s - CSS and Jquery not allowed for animation.
var e = document.getElementById("aDiv");
var s = 1;
function myInterval() {
var eLeftPos = e.offsetLeft;
//console.log(e.offsetLeft);
e.style.left = (eLeftPos + s) + 'px';
//console.log(e.style.left);
var leftPos = (eLeftPos + s) >= 300
if (leftPos) {
function myInterval1() {
var eTopPos = e.offsetTop;
//console.log(e.offsetLeft);
e.style.top = (eTopPos + s) + 'px';
//console.log(e.style.top);
if ((eTopPos + s) >= 100){
clearInterval(internal1)
}
}
var internal1 = setInterval(myInterval1, 100);
}
if ((eLeftPos + s) >= 300){
clearInterval(internal)
}
}
var internal = setInterval(myInterval, 100);
Try Using CSS methods instead of Javascript. Try this:
CSS Animation from Left to Right
or this: How to animate sliding-in text form left to right

Using animate.css (link in description) how do I trigger an animation when a particular event is finished

I have an an image moving across the screen and out of viewport, when the image reaches a particular absolute position (right: - 200), I want to trigger the below animation. I am relatively new to programming, not sure how to track when a particular function is done so that I can trigger the below animation.
var $startLessonButton = $('.startLessonButtonUp');
$startLessonButton.mouseup(function() {
$(this).addClass('animated slideInLeft');
});
---------
var movingOutAnimationCounter = 2;
var movingOutCurrentPosition = window.innerWidth / 2 - 200
function moveTrumpOut() {
movingOutCurrentPosition -= 2;
trumpyWrapper.style.right = movingOutCurrentPosition + 'px';
if (movingOutAnimationCounter < 9 ) {
trumpy.src = '../images/trump_walking_out_' + movingOutAnimationCounter + '.png';
movingOutAnimationCounter += 1;
} else {
movingOutAnimationCounter = 1;
trumpy.src = '../images/trump_walking_out_' + movingOutAnimationCounter + '.png';
}
if (movingOutCurrentPosition > -200 ) {
requestAnimationFrame(moveTrumpOut);
}
}
All the best!
If you know time, when moving element is hidden, you can use this function:
setTimeout(function(){ $('.elem').addClass("animCssClass") }, 1000);
Last parameter, in this example: 1000 is time in ms, when function inside should execute. Run this function on mouseup when you adding class to moving element.

Window scroll function lag

I have a function that positions a div depending on the webpages position.
function calcNav(){
var b = $('#breadcrumb').offset().top;
var w = $(window).scrollTop();
var x = b - w;
//console.log('breadcrumb from top = ' + b + ' window scrolled = ' + w + ' position of nav = ' + x);
$('.sub-nav').css('top', x);
}
calcNav();
$(window).scroll(calcNav);
The function works great, my only issue is that as its constantly rendering my page speed appears a bit laggy - is there any way I can run the function at the end of the scroll instead of during?
I would recommend to you use it with combination with setTimeout and add small amount of milliseconds:
var scrollTimeout;
$(window).scroll(function() {
clearTimeout( scrollTimeout );
scrollTimeout = setTimeout( calcNav, 50 );
});
clearTimeout in this case is used to not trigger previous call if next scroll event was triggered less than 50ms, in case you think your users will scroll slower you can increase this value for example to 100ms etc.

Change position of last image

The code:
function showLetter() {
setInterval(function() {
var letter = imgsArray[random()];
var top = random();
var left = random();
$("div").append("<img src='imgs/" + letter + ".png'>");
$("div").last().css({"position": "absolute", "top": top + "px", "left": left + "px"});
}, 1000);
}
In each position of the array imgsArray, I have the name of an image.
What I want to do:
Add an image every 1000 ms, giving it a random position on the screen. (If it's possible to prevent overlapping, that'd be great, but I think that has already been answered).
What it does:
Every 1000 ms, it adds a new image of a letter, and gives the same properties to all images so they all end up horizontally aligned :)
I really don't understand why this is happening. With $("div").last().css(), am I not choosing the last image added to the div and changing only its properties?
Thanks in advance.
$("div").last() gives you the last item in the `$("div") jquery object. There are no images in that jQuery object.
Perhaps what you want is:
$("div img").last()
But, that is quite inefficient. If you just want to operate on the newly created image object, then you can just operate on it directly:
function showLetter() {
setInterval(function() {
var letter = imgsArray[random()];
var top = random();
var left = random();
var img = $("<img src='imgs/" + letter + ".png'>");
img.css({"position": "absolute", "top": top + "px", "left": left + "px"});
$("div").append(img);
}, 1000);
}
You might want to consider something like this:
var div = $('<div/>').css({position:'absolute'....}).appendTo('body');
var img = $('<img/>', {src:'imgs/' + letter + '.png'}).appendTo(div);
This will add new <div> containing an image to <body>.

function doesn't execute on jquery document ready

I have a javascript function that resize and centers images based on the surrounding container size (that in turn depend on the window size). I use jquery as js framework. The function need to be executed after document load (on document ready) but also when and if the user changes size of the browser, ie I have the following running in the html-document:
$(document).ready(function(){
fixImageSizes();
});
$(window).resize(function() {
fixImageSizes();
});
But for some unknown reason the function is only executed when a user resizes the browser and not after loading. Can anyone please help with this?
(my function is below for knowledge...)
function fixImageSizes()
{
var cw = $('#imagecontainer').width();
var ch = $('#imagecontainer').height();
$('#imagecontainer img').each(function()
{
var iw = $(this).css('width');
var ih = $(this).css('height');
if (parseInt(iw) < parseInt(cw)) // image width < viewport
{
var newih = Math.ceil(parseInt(ih) * parseInt(cw) / parseInt(iw)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(newih)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(cw)/2) + 'px';
$(this).css({'width':cw,'height':newih,'margin-left':newimarginl,'margin-top':newimargint});
}
if (parseInt(ih) < parseInt(ch)) // image height < viewport
{
var newiw = Math.ceil(parseInt(iw) * parseInt(ch) / parseInt(ih)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(ch)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(newiw)/2) + 'px';
$(this).css({'width':newiw,'height':ch,'margin-left':newimarginl,'margin-top':newimargint});
}
if (parseInt(ih) > parseInt(ch) && parseInt(iw) > parseInt(cw)) // viewport smaller than image, shrink image
{
if (parseInt(ch) - parseInt(ih) > parseInt(cw) - parseInt(iw)) // difference is less on height
{
var newiw = Math.ceil(parseInt(iw) * parseInt(ch) / parseInt(ih)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(ch)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(newiw)/2) + 'px';
$(this).css({'width':newiw,'height':ch,'margin-left':newimarginl,'margin-top':newimargint});
}
else // difference less on width
{
var newih = Math.ceil(parseInt(ih) * parseInt(cw) / parseInt(iw)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(newih)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(cw)/2) + 'px';
$(this).css({'width':cw,'height':newih,'margin-left':newimarginl,'margin-top':newimargint});
}
}
});
You should use the load event instead of the ready event.
The ready event runs after the document has loaded, but before the images has loaded, so you won't have the correct size of all elements.
The function is probably executing (you can double-check with a simple alert), but the images you are "fixing" is probably not loaded yet. You can use the window.onload event or listen to the image load event like this:
var scale = function() {
// rescale
};
$('#imagecontainer img').each(function() {
this.complete ? scale.call(this) : $(this).load(scale);
});
Try this:
$(window).load(function (){
fixImageSizes();
});

Categories

Resources