Moving a div right animation not working - javascript

I am trying implement a small animation on a div. Whenever we click on the div it has to move right. I wrote some code but it is not working. Could anyone please help me?
here is my code
<style type="text/css">
#animDiv
{
background-color:#6F0;
width:87px;
height:39px;
left:10px;
}
</style>
<script>
function $(id)
{
return document.getElementById(id);
}
function moveRight()
{
var elem = $("animDiv");
//var divPos = parseInt($("animDiv").style.left);
var divPos = $("animDiv").offsetLeft;
var divWid = $("animDiv").offsetWidth;
if(divPos+divWid < 700)
{
$("animDiv").style.left = $("animDiv").style.left+100+"px";
}
}
</script>
<body>
<div id="animDiv" onclick="moveLeft()">
</div>
</body>

try replacing this code
<div id="animDiv" onclick="moveLeft()">
with this code
<div id="animDiv" onclick="moveRight()">
and add style position:fixed; to your css.

There are several issues in your code:
You are calling the wrong function. It is declared moveRight()
You are attempting to change the left property which will have no affect on elements that are positioned statically.
The element will only nudge right one time. After that the value for your left property is something like 100px100px.
How is this:
function moveRight() {
var elem = $("animDiv");
//var divPos = parseInt($("animDiv").style.left);
var divPos = $("animDiv").offsetLeft;
var divWid = $("animDiv").offsetWidth;
if (divPos + divWid < 700) {
var curLeft = Number($("animDiv").style.left.replace("px", ""));
$("animDiv").style.left = (curLeft + 100) + "px";
}
}
JSFiddle

Related

Addclass when div width is greater than 80%

How to addclass when div width is greater than 80% ?
This is what I just tried
<div class="wrap_bar">
<div class="bar" style="width:50%;"></div>
</div>
<div class="box"></div>
<script>
var barTotal = $(".bar");
var box= $(".box");
var width = barTotal.width();
if (width > 80%)
box.addClass('type2')
</script>
This code is not working well. Please help
If you need this dimension detection only one time (when DOM loaded) then you can just following approach.
function addWhenResized(element){
var parentWidth = $(element).parent().width();
var elementWIdth = $(element).width();
if( (elementWIdth / parentWidth)*100 > 79){
$('.box').addClass('type2');
}
else {
$('.box').removeClass('type2');
}
}
$(document).ready(function(){
addWhenResized('.bar');
})
But main challenge will be there if you want detect the run time dimension change. Then need to take help from here: http://marcj.github.io/css-element-queries/
After added the plugins from above given link you should follow the following approach:
function addWhenResized(element){
var parentWidth = $(element).parent().width();
var elementWIdth = $(element).width();
if( (elementWIdth / parentWidth)*100 > 79){
$('.box').addClass('type2');
}
else {
$('.box').removeClass('type2');
}
}
new ResizeSensor(jQuery('.bar'), function(){
addWhenResized('.bar');
});
Try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var barTotal = $(".bar");
var barTotalWidth = barTotal.width();
var box= $(".box");
var boxWidth = box.width();
var widthPercent = boxWidth / barTotalWidth;
console.log(widthPercent);
if (widthPercent > 0.8)
box.addClass('type2');
});
</script>
<div class="bar" style="width:200px;height:100px;background-color:red"> </div>
<div class="box" style="width:190px;height:80px;background-color:blue"> </div>
your codes don't work because you've just called javascript once when the page loaded , you have to wrap it into an event !
Take a look
that answer
or that answer
jQuery(document).ready(function($) {
if ($(this).width() > 768) {
$('#service-1').addClass('row text-center');
} else {
$('#service-1').removeClass('row text-center');
}
});
this will work fantastic when width is less than or more than will add or remove the class

Change opacity of header DIV using YUI

Hey I have a div with "#header1" which I would like to keep at the top of the page as a user scrolls down. Now, I managed to get the div stick to the top upon scroll using "position:fixed" on "#header1" and what I would like to do now is change the opacity of the "#header1" once I scroll down and back to it's opaque state if i'm scrolled back up. I previously had posted my code but then learned we can use only YUI. Any advice would help. I am a total novice when it comes to YUI.
HTML:
<div id="header1">Hello</div>
CSS:
#header1 {
position: fixed;
top:0px;
z-index:1000;
margin:0;
padding:10px;
}
JS:
var target = $('div#header1');
var targetHeight = target.height();
var scrollRange = maxScroll/(target.length-1);
$(document).scroll(function(e){
var scrollY = $(window).scrollTop();
var scrollPercent = (scrollRange - scrollY%scrollRange)/scrollRange;
var divIndex = Math.floor(scrollY/scrollRange);
target.has(':lt(' + divIndex + ')').css('opacity', 0);
target.eq(divIndex).css('opacity', scrollPercent);
target.has(':gt(' + divIndex + ')').css('opacity', 1);
});
You can try something like the following:
var notScrolled = true;
var headerTop = $('header').height(); // header size
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > headerTop && notScrolled) {
$('header').css('opacity',0.2);
notScrolled = false;
} else if (scrollTop < headerTop && !notScrolled){
$('header').css('opacity',1);
notScrolled = true;
}
});
Demo Fiddle

How to move DIV pixel by pixel

I have a DIV setup like this.
<div id="parent" class="parent">
<div id="child" class="child">
</div>
</div>
Styles
<style>
.parent{
float:left; height:300; width:300px; background-color:#00ff00;
}
.child{
float:left; height:60; width:60px; background-color:#00ff00;
}
</style>
<script>
function move(){
while(m < 100){
document.getElementByid('child').style.marginTop = m;
m = m+1;
}
}
move();
</script>
I want to move inner DIV ( named child) pixel by pixel from top to bottom by 100 pixels.
I think it can be done using style.marginTop = '' and settimeout() function
But still not able to get this working.
Here is how you can animate your div with vanilla JavaScript: http://jsfiddle.net/z6F7m/1/
JavaScript
var elem = document.getElementById('animated'),
top = parseInt(elem.style.marginTop, 10) || 0,
step = 1;
function animate() {
if (top < 100) {
requestAnimationFrame(animate);
elem.style.marginTop = top + 'px';
top += step;
}
}
animate();
I highly recommend you to use requestAnimationFrame instead of setTimeout, if the browser does not supports requestAnimationFrame you can fallback to setTimeout.
Try this
var element = document.getElementById('child');
for (var i=0; i != 100; i++){
element.style.marginTop += 1;
}
That'll loop 100 times and add 1 to the marginTop each loop.
I'd suggest using jQuery thought, because with jQuery you can simply do
$("#child").animate({ marginTop: 100 });
EDIT
Top example doesn't make sense, try this.
var element = document.getElementById('animated');
for (var i = 0; i != 100; i++) {
currentTop = parseInt(element.style.marginTop) || 0;
newTop = parseInt(currentTop + 1);
element.style.marginTop = newTop + "px";
}
This is also stupid because it loops way to fast and by the time the browser renders the box, it's already 100px from the top. See here
Again, go with the jQuery solution.
One way of doing it is using jQuery's animate function, which would require merely writing:
$(element).animate({ 'top': '100px' });
Example
Check the following fiddle. I did it without jquery.
var step = 0;
window.setInterval(function(){
var value = (++step)*100;
if (value<300)
document.getElementById("child").style.marginTop=value+"px";
else
step = -1;
},1000);
http://jsfiddle.net/pasindur/EbHt5/

modifying a sliding javascript div

I got some code off the net to make a box slide in. However it slid in from the top left and I wanted it to slide in from the bottom. I changed the css position from top:-200px to bottom:-200px and changed the part of the code that alters the position from
{
popup.style.top = (currentTop + speed) + "px";
keepMoving = true;
}
to
{
popup.style.bottom = (currentTop + speed) + "px";
keepMoving = true;
}
now it doesn't work. I cannot see what variable I should be making. Here is the full code (which works if I change them back to 'top')
<html>
<head>
<title>Moving Pop Up Samplet</title>
<style>
#popup
{
height:200px;
width:200px;
border:1px solid #000;
background:#CC9900;
position:absolute;
bottom:-200px;
left:-200px;
}
</style>
<script>
var timer = null;
var speed = 3; //1 is slow
var endTop = 0;
var endLeft = 0;
//******************************************************
// Simple little function to get Elements as an object
//******************************************************
function getEl(id)
{
var el = document.getElementById(id);
return el;
}
//******************************************************
// Function to show Elements
//******************************************************
function showEl(id)
{
getEl(id).style.display ="";
}
//******************************************************
// Function to hide Elements
//******************************************************
function hideEl(id)
{
getEl(id).style.display ="none";
}
//******************************************************
// Function to move Element
//******************************************************
function moveEl(id)
{
var popup = getEl(id);
var currentTop = parseInt(popup.offsetTop);
var currentLeft = parseInt(popup.offsetLeft);
var keepMoving = false;
//Move
if (currentTop <= endTop)
{
popup.style.bottom = (currentTop + speed) + "px";
keepMoving = true;
}
if(currentLeft <= endLeft)
{
popup.style.left = (currentLeft + speed) + "px";
keepMoving = true;
}
if (keepMoving)
{
startMove(id);
}
else
{
endMove();
}
}
//******************************************************
// Function to start the move
//******************************************************
function startMove(id)
{
timer = setTimeout("moveEl('"+id+"')", 1);
}
//******************************************************
// Function to end the move
//******************************************************
function endMove()
{
clearTimeout(timer);
}
</script>
</head>
<body onload="startMove('popup');">
<!-- POP UP DIV -->
<div id="popup">
<center><span onclick="hideEl('popup');" style="cursor:pointer;"> Close</span></center>
</div>
<!--END POP UP DIV -->
<center><span onclick="startMove('popup');" style="cursor:pointer;"> Show Pop Up</span></center>
</body>
</html>
You'll just need to rejiggle your inequalities a bit.
Given that there's no offset bottom property in javascript, it'll be easier to still work with top values, even if you want to come in from the bottom.
function moveEl(id) {
var popup = getEl(id);
var currentTop = parseInt(popup.offsetTop);
var currentLeft = parseInt(popup.offsetLeft);
var keepMoving = false;
//Move
if (currentTop >= endTop) {
popup.style.top = (currentTop - speed) + "px";
keepMoving = true;
}
if (currentLeft <= endLeft) {
popup.style.left = (currentLeft + speed) + "px";
keepMoving = true;
}
if (keepMoving) {
startMove(id);
}
else {
endMove();
}
}
Here's a working jsFiddle.
If you think about the way the function is checking to see if it's finished yet, and adding on the speed variable each time, you should be able to step through the original version compared to this and see how the logic is working.
Instead writing something from scratch consider using jQuery's slideToggle method.

Javascript Marquee to replace <marquee> tags

I'm hopeless at Javascript. This is what I have:
<script type="text/javascript">
function beginrefresh(){
//set the id of the target object
var marquee = document.getElementById("marquee_text");
if(marquee.scrollLeft >= marquee.scrollWidth - parseInt(marquee.style.width)) {
marquee.scrollLeft = 0;
}
marquee.scrollLeft += 1;
// set the delay (ms), bigger delay, slower movement
setTimeout("beginrefresh()", 10);
}
</script>
It scrolls to the left but I need it to repeat relatively seamlessly. At the moment it just jumps back to the beginning. It might not be possible the way I've done it, if not, anyone have a better method?
Here is a jQuery plugin with a lot of features:
http://jscroller2.markusbordihn.de/example/image-scroller-windiv/
And this one is "silky smooth"
http://remysharp.com/2008/09/10/the-silky-smooth-marquee/
Simple javascript solution:
window.addEventListener('load', function () {
function go() {
i = i < width ? i + step : 1;
m.style.marginLeft = -i + 'px';
}
var i = 0,
step = 3,
space = ' ';
var m = document.getElementById('marquee');
var t = m.innerHTML; //text
m.innerHTML = t + space;
m.style.position = 'absolute'; // http://stackoverflow.com/questions/2057682/determine-pixel-length-of-string-in-javascript-jquery/2057789#2057789
var width = (m.clientWidth + 1);
m.style.position = '';
m.innerHTML = t + space + t + space + t + space + t + space + t + space + t + space + t + space;
m.addEventListener('mouseenter', function () {
step = 0;
}, true);
m.addEventListener('mouseleave', function () {
step = 3;
}, true);
var x = setInterval(go, 50);
}, true);
#marquee {
background:#eee;
overflow:hidden;
white-space: nowrap;
}
<div id="marquee">
1 Hello world! 2 Hello world! 3 Hello world!
</div>
JSFiddle
I recently implemented a marquee in HTML using Cycle 2 Jquery plugin :
http://jquery.malsup.com/cycle2/demo/non-image.php
<div class="cycle-slideshow" data-cycle-fx="scrollHorz" data-cycle-speed="9000" data-cycle-timeout="1" data-cycle-easing="linear" data-cycle-pause-on-hover="true" data-cycle-slides="> div" >
<div> Text 1 </div>
<div> Text 2 </div>
</div>
HTML5 does not support the tag, however a lot of browsers will still display the text "properly" but your code will not validate. If this isn't an issue for you, that may be an option.
CSS3 has the ability, supposedly, to have marquee text, however because anyone that knows how to do it believes it's a "bad idea" for CSS, there is very limited information that I have found online. Even the W3 documents do not go into enough detail for the hobbyist or self-teaching person to implement it.
PHP and Perl can duplicate the effect as well. The script needed for this would be insanely complicated and take up much more resources than any other options. There is also the possibility that the script would run too quickly on some browsers, causing the effect to be completely negated.
So back to JavaScript - Your code (OP) seems to be about the cleanest, simplest, most effective I've found. I will be trying this. For the seamless thing, I will be looking into a way to limit the white space between end and beginning, possibly with doing a while loop (or similar) and actually run two of the script, letting one rest while the other is processing.
There may also be a way with a single function change to eliminate the white space. I'm new to JS, so don't know off the top of my head. - I know this isn't a full-on answer, but sometimes ideas can cause results, if only for someone else.
This script used to replace the marquee tag
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.scrollingtext').bind('marquee', function() {
var ob = $(this);
var tw = ob.width();
var ww = ob.parent().width();
ob.css({ right: -tw });
ob.animate({ right: ww }, 20000, 'linear', function() {
ob.trigger('marquee');
});
}).trigger('marquee');
});
</script>
<div class="scroll">
<div class="scrollingtext"> Flash message without marquee tag using javascript! </div>
</div>
Working with #Stano code and some jQuery I have created a script that will replace the old marquee tag with standard div. The code will also parse the marquee attributes like direction, scrolldelay and scrollamount.
Here is the code:
jQuery(function ($) {
if ($('marquee').length == 0) {
return;
}
$('marquee').each(function () {
let direction = $(this).attr('direction');
let scrollamount = $(this).attr('scrollamount');
let scrolldelay = $(this).attr('scrolldelay');
let newMarquee = $('<div class="new-marquee"></div>');
$(newMarquee).html($(this).html());
$(newMarquee).attr('direction',direction);
$(newMarquee).attr('scrollamount',scrollamount);
$(newMarquee).attr('scrolldelay',scrolldelay);
$(newMarquee).css('white-space', 'nowrap');
let wrapper = $('<div style="overflow:hidden"></div>').append(newMarquee);
$(this).replaceWith(wrapper);
});
function start_marquee() {
let marqueeElements = document.getElementsByClassName('new-marquee');
let marqueLen = marqueeElements.length
for (let k = 0; k < marqueLen; k++) {
let space = ' ';
let marqueeEl = marqueeElements[k];
let direction = marqueeEl.getAttribute('direction');
let scrolldelay = marqueeEl.getAttribute('scrolldelay') * 100;
let scrollamount = marqueeEl.getAttribute('scrollamount');
let marqueeText = marqueeEl.innerHTML;
marqueeEl.innerHTML = marqueeText + space;
marqueeEl.style.position = 'absolute';
let width = (marqueeEl.clientWidth + 1);
let i = (direction == 'rigth') ? width : 0;
let step = (scrollamount !== undefined) ? parseInt(scrollamount) : 3;
marqueeEl.style.position = '';
marqueeEl.innerHTML = marqueeText + space + marqueeText + space;
let x = setInterval( function () {
if ( direction.toLowerCase() == 'left') {
i = i < width ? i + step : 1;
marqueeEl.style.marginLeft = -i + 'px';
} else {
i = i > -width ? i - step : width;
marqueeEl.style.marginLeft = -i + 'px';
}
}, scrolldelay);
}
}
start_marquee ();
});
And here is a working codepen
I was recently working on a site that needed a marquee and had initially used the dynamic marquee, which worked well but I couldn't have the text begin off the screen. Took a look around but couldn't find anything quite as simple as I wanted so I made my own:
<div id="marquee">
<script type="text/javascript">
let marquee = $('#marquee p');
const appendToMarquee = (content) => {
marquee.append(content);
}
const fillMarquee = (itemsToAppend, content) => {
for (let i = 0; i < itemsToAppend; i++) {
appendToMarquee(content);
}
}
const animateMarquee = (itemsToAppend, content, width) => {
fillMarquee(itemsToAppend, content);
marquee.animate({left: `-=${width}`,}, width*10, 'linear', function() {
animateMarquee(itemsToAppend, content, width);
})
}
const initMarquee = () => {
let width = $(window).width(),
marqueeContent = "YOUR TEXT",
itemsToAppend = width / marqueeContent.split("").length / 2;
animateMarquee(itemsToAppend, marqueeContent, width);
}
initMarquee();
</script>
And the CSS:
#marquee {
overflow: hidden;
margin: 0;
padding: 0.5em 0;
bottom: 0;
left: 0;
right: 0;
background-color: #000;
color: #fff;
}
#marquee p {
white-space: nowrap;
margin: 0;
overflow: visible;
position: relative;
left: 0;
}

Categories

Resources