JQuery animate margin-top using var not working - javascript

I'm using JQuery to have my .wrapper div snap back to its original margin-top after being moved to margin-top. The original margin-top is dependent on browser height. I'm trying to do this by storing the original margin-top value into a variable, and using it for JQuery animate when I want to .wrapper div to snap back later on.
$(document).ready(function() {
//Adjust .wrapper Margin-top to adjust position to 1/4 of Window Broswer Height
var marginWindowSpace = ($(window).height()) / 4;
$(".wrapper").css("margin-top", marginWindowSpace);
var originalMargin = $(".wrapper").css("margin-top").toString();
});
$(".title").click(function() {
$("#results-container").empty();
$(".wrapper").animate({
'margin-top': originalMargin
}, 200);
$(".title-tag, .or, .random-article, .random-article-underline").fadeIn(500);
$("footer").addClass("footer-pos1");
});
QUESTION: Why wont my the animate margin-top accept my variable (where the original margin-top value is stored), even when converted to string? I don't want to use a static value as my margin-top.
If you want to see the app code, it's here. http://codepen.io/myleschuahiock/pen/zqvvNZ
Any help is appreciated! Thanks!
EDIT: I changed the click function to $('.go-back'), but the animate for magin-top should still be the same

Move the whole $(".title").click(function(){}) into the $(document).ready(function(){})
The problem exists because at the time of the initialisation of the $(".title").click(function(){}) originalMargin is not set yet because the document is not ready yet.

Do like this. there are some errors in your animate part.margin-top should be correct as marginTop and your string should convert as int and do like this.I implement as an example.hope this will help to you.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<style type="text/css">
body{
margin: 0;
padding: 0;
}
div.testing{
width: 100px;
height: 100px;
background-color: orange;
margin-top: 100px;
}
div.two{
width: 200px;
height: 200px;
background-color: green;
position:
}
</style>
<body>
<div class="testing"></div>
<br><br>
<h3 class="clk">Click me!</h3>
<div class="two"></div>
<script type="text/javascript">
$(document).ready(function(){
var one = $(".testing").css("margin-top").toString();
var vaL = parseInt(one,10);
$(".clk").click(function(){
$(".two").animate({'marginTop':vaL+'px'},1000);
});
});
</script>
</body>
</html>
note :
var one = $(".testing").css("margin-top").toString();
int this part get the margin-top value as a string.
var vaL = parseInt(one,10);
convert it to an integer.
then the animate part
$(".two").animate({'marginTop':vaL+'px'},1000);

Related

CSS animation / transition not working properly

Here is without animation / transition code check this:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<style>
.resize {
font-size: 2.8vh;
white-space: nowrap;
color: black;
background: yellow;
cursor: move;
width: 300px;
height: 130px
}
</style>
</head>
<body>
<button class="do-resize" type="button" >Click Me!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/smoothness/jquery-ui.css">
<div class="resize" id="chartdiv">Some name that is very long</div>
</body>
</html>
<script type="text/javascript">
$.fn.fontResize = function() {
return this.each(function() {
const $el = $(this);
$el.css('font-size', ($el.width() * $el.height()) / 2800 + 'px');
});
}
$('button.do-resize').click(function(){
$('#chartdiv').width(600).fontResize()// use plugin function
})
$('.resize').resizable({
minWidth: 210,
minHeight: 120,
resize: function(event, ui) {
$(this).fontResize();// use plugin function
}
});
</script>
</body>
</html>
and now this is with animation / transition code: simply i have added here only CSS transition for div class .resize{transition: 0.3s;} and i think it should work, But problem is that this is not working with single click, if i click one time then text font-size goes small and then after second click it works, what is the problem plz check it. i want to work it with single click only.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<style>
.resize {
font-size: 2.8vh;
white-space: nowrap;
color: black;
background: yellow;
cursor: move;
width: 300px;
height: 130px
}
.resize{transition: 0.3s;}
</style>
</head>
<body>
<button class="do-resize" type="button" >Click Me!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/smoothness/jquery-ui.css">
<div class="resize" id="chartdiv">Some name that is very long</div>
</body>
</html>
<script type="text/javascript">
$.fn.fontResize = function() {
return this.each(function() {
const $el = $(this);
$el.css('font-size', ($el.width() * $el.height()) / 2800 + 'px');
});
}
$('button.do-resize').click(function(){
$('#chartdiv').width(600).fontResize()// use plugin function
})
$('.resize').resizable({
minWidth: 210,
minHeight: 120,
resize: function(event, ui) {
$(this).fontResize();// use plugin function
}
});
</script>
</body>
</html>
If you check the calculated font size you'll find some issues:
So my assumption is that, since you're transitioning all CSS properties (by setting transition: 0.3s you're not excluding any property change), the width of .resize is not 600px by the time you're calculating the new font-size. Try with a longer transition time, like 2 seconds. You will probably need more than 2 clicks to get the final font-size. If that happens, then you found the problem.
A solution, in case you want to transition also the width change, would be to pass the desired width (600px) to fontResize() and not rely on the HTML element width (which will be changing for .3 seconds).
The text is resizing immediately - the problem is that the resize function takes the initial dimensions of the yellow rectangle as the measures for the resizing - not the final dimensions after the animation completes. So the text is resizing to the same size and you see no difference.
When you click the button, you're telling the text to resize to the yellow rectangle's size. But the yellow rectangle isn't fully resized at this point, basically the text element is being resized relative to the initial dimensions of the yellow rectangle.
To verify this, you only have to apply a setTimeout to the text animation, and you'll see, that if the yellow rectangle has time to animate, the text element will animate as you expect it to.
To see the what I mean, replace the click handler with the following code.
$('button.do-resize').click(function() {
$('#chartdiv').width(600)
setTimeout(function() {
$('#chartdiv').fontResize()
}, 300)
})
So you see, if you give time for the rectangle to expand, the text will be able to get larger dimentions from it to expand.
But if you hardcode the final font size, the animation will start immediately
Instead of:
$el.css('font-size', ($el.width() * $el.height()) / 2800 + 'px');
Try:
$el.css('font-size','40px');
The point is, make sure to determine appropriate dimensions at the time of the button click.
Add the following:
$('#chartdiv').on('transitionend', function () {
$(this).fontResize()
});
You trigger the fontResize() each time a transition end to make sure you use the correct div.
$.fn.fontResize = function() {
return this.each(function() {
const $el = $(this);
$el.css('font-size', ($el.width() * $el.height()) / 2800 + 'px');
});
}
$('button.do-resize').click(function() {
$('#chartdiv').width(Math.random()*600).fontResize() // use plugin function
})
$('#chartdiv').on('transitionend', function () {
$(this).fontResize()
});
$('.resize').resizable({
minWidth: 210,
minHeight: 120,
resize: function(event, ui) {
$(this).fontResize(); // use plugin function
}
});
.resize {
font-size: 2.8vh;
white-space: nowrap;
color: black;
background: yellow;
cursor: move;
width: 300px;
height: 130px
}
.resize {
transition: 0.3s;
}
<button class="do-resize" type="button">Click Me!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/smoothness/jquery-ui.css">
<div class="resize" id="chartdiv">Some name that is very long</div>
Since you are hard-coding the final width in the click handler by doing $('#chartdiv').width(600), you might as well pass that as a parameter to help you resize the text.
Instead of something like this:
$el.css('font-size', ($el.width() * $el.height()) / 2800 + 'px');
Something more like this:
$el.css('font-size', (parameter * parameter) / 2800 + 'px');
Here's a working JSFiddle.
In my example, everything will animate immediately to the right place.
See the comments where I made changes:
$.fn.fontResize = function(newSize) { // receive parameter
return this.each(function() {
$el = $(this)
const halfSize = newSize/2 // divide width by 2
$el.css('font-size', (halfSize * halfSize) / 2800 + 'px'); // apply in calculation
});
}
$('button.do-resize').click(function(){
const newSize = 600 // declare as const to use twice in next line
$('#chartdiv').width(newSize).fontResize(newSize) // pass as parameter to fontResize
})

how to change image when scrolling webpage [html, javascript]

Hi i need to modify java script that will by changing fixed image.
In for example:
when page is loaded then image will by on right site. Next after scrolling down page image should be changed to next one for each e.g. 100px. Images need to by loaded from image list or something similar.
I have found java script that make something similar to this. [Instead of creating images of numbers i need to load my own images]
<!DOCTYPE html>
<html>
<head>
<style>
html,body {
height: 400%;
background: white;
width: 100%;
}
.show {
width: 100px;
height: 100px;
position: fixed;
top: 300px;
right: 20px;
background: lime;
}
</style>
</head>
<body>
<img class="show" alt="0" src="img0.jpg" />
Text,Text,Text,Text,Text,Text,Text,Text,Text,Text,Text
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript" src="jquery.easing.1.3.js"></script>
<script type="text/javascript">
var lastI
$(window).scroll(function() {
var scrollTop = $(this).scrollTop()
console.log(scrollTop)
var i = (scrollTop / 10).toFixed(0)
if (i !== lastI)
$(".show").attr({
"src": "img" + i + ".jpg",
"alt": i
})
lastI = i
})
</script>
</body>
</html>
Update:09.11.2017
Ok, I manage this code to work. What should I do it was to setup right path to image files like in my case ("src": "test/" + i + ".jpg",) where my images are in "test" folder, and change names of images [1.jpg, 2.jpg and so on].
You can easyli change your image with Native scroll event, without using JQuery :
You can see how to use native scroll event here
<body>
<!-- This is an image with a 'show' id -->
<img id="show" alt="0" src="img0.jpg" />
<script type="text/javascript">
/* this capture the `scroll event`*/
window.addEventListener('scroll', function(e) {
/* This generate a image name in case with scroll position (ex img1.jpg) */
let bgImage = 'img' + (window.scrollY / 10 ).toFixed(0) + '.jpg';
/* This specify the path where are your images list */
let bgImagePath = '../images/' + bgImage;
/* This get your element (img) with id `show` and change this background image by the path include in `bgImagePath` variable */
document.getElementById('show').style.backgroundImage = bgImagePath;
});
</script>
</body>
Native background image explain here
Native getElementById explain here
This sample of code do not use JQuery :) Just native Javascript : you van remove this lines in your code :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript" src="jquery.easing.1.3.js"></script>
Hope I help you.
I'am not sure, try this one:
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y > 100) {
$('.Classname').css("background-image","../images/image.png");
} else {
$('.Classname').css("background-image","none");
}
});

How can I call a CSS animation on a nested element within a parent element?

I'm looking to remove a class from a nested div element upon focus of the parent. Then I want to replace the class with another that has a CSS animation that will autoplay. I'm looking to do this within multiple elements in the same class as well so it will need to be able to handle more than one. I'm not sure what to do as I've kind of reached to where I believe I should be at this point but to no avail.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<style>
<style>
div {
filter: opacity(0%);
background-color: red;
width: 300px;
height: 300px;
position: relative;
top: 50%;
left: 50%;
z-index: 1;
}
.noGrow {
}
.grow {
animation-name: derp;
animation-duration: 1s;
filter: opacity(100%);
}
#keyframes derp {
from{width: 0px;}
to{width: 300px;}
}
</style>
<body>
<span id="divHolder" tabindex="1">
<div class="noGrow firstDiv">
</div>
</span>
</body>
<script src="jquery.js"> </script>
<script>
var divHolder = $(".divHolder");
var firstDiv = $(".firsDiv");
divHolder.focus(function () {
if($(".firstDiv").hasClass("noGrow")){
$(this).removeClass("noGrow");
$(this).addClass("grow");
console.log("It's working.");
}
});
</script>
</html>
Thank you for any and all help. It is much appreciated.
Looking at your code, these two lines seem to be the problem:
$(this).removeClass("noGrow");
$(this).addClass("grow");
$(this) refers to the divHolder element you are binding the focus event to. If you want to change the class of firstDiv, you'll need to change the lines to this:
firstDiv.removeClass('noGrow');
firstDiv.addClass('grow');
However, based on your CSS, I would suggest using toggleClass, and leaving the noGrow class off completely. Your div becomes:
<div class="firstDiv"></div>
and your JS becomes:
divHolder.focus(function () {
firstDiv.toggleClass('grow');
console.log('growing!');
});
Finally, if you don't know where in the list of descendants your 'growable' div will be, you can use something like find():
divHolder.focus(function(){
$(this).find('div').toggleClass('grow');
// if the div is given an id like #growable we can do this:
// $(this).find('#growable').toggleClass('grow');
});

I have a Div Element acting as a button but it will only work once

I am 11 years old and I started learning Javascript a couple of months ago, So I am trying to make a page where if you scroll down too much it will take you back to the top so I made a Div element that fills up a large space and onmouseover it will take you back up to the top but if you try it a second time it won't do anything. Please help. Thanks in advance !
I hope my understanding of your problem is right. You have a div and you want to go up each time you scroll too much.
As an example of how to handle the scroll in vanilla JavaScript you can have a look at the document for the onscroll event: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onscroll.
Here is an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<style>
#container {
height: 500px;
width: 515px;
overflow: auto;
}
#foo {
height: 1000px;
width: 500px;
background-color: #777;
}
</style>
</head>
<body>
<div id="container">
<div id="foo"></div>
</div>
<script>
var container = document.getElementById('container');
container.addEventListener('scroll', function(event) {
// Get top and left value
var top = container.scrollTop
if (top > 400) {
// Go to the top
container.scrollTop = 0;
}
}, false);
</script>
</body>
</html>
In this example the contained element is bigger that the container so the container becomes scrollable with the overflow: auto; css property.
The scripts applies a onscroll event that checks the scroll value of the container and reset it to 0 when it exceed an arbitrary value (400 in the example).
I hope this has been useful to your work.

Can't get scrollTop() to work in both Chrome & Firefox

I am having trouble getting the scrollTop() method to work in both Firefox and Chrome. I used $('body, html').scrollTop(); however, it doesn't work in Chrome. Only $('body').scrollTop(); works in Chrome. Any thoughts would be greatly appreciated. Below is my code.
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style type="text/css">
body {
height: 2000px;
}
#light {
display: block;
position: fixed;
top: 50%;
left: 50%;
margin-left: -400px;
margin-top: -200px;
width: 800px;
height: 400px;
background-color: blue;
z-index:1002;
overflow: auto;
}
</style>
</head>
<body>
<div id="light">
</div>
<!-- Used the google jQuery link for ease of use in this example -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(window).scroll(function () {
var offset = $('body, html').scrollTop();
var view = $(window).height();
var total = $(document).height();
var percent = 1-(offset / (total - view));
var widthFactor = 800*percent;
var marginFactor = -(400*percent)
if(percent > 0.33){
$("#light").css({ "width" : widthFactor,
"margin-left" : marginFactor});
};
});
});
</script>
</body>
</html>
Use the document object instead
$(document).scrollTop();
I had this same issue. Best solution for me was to do it on window:
var offset = $(window).scrollTop();
In order for this to work though, your body and html elements can't have a height set to 100%. use min-height instead
EDIT: the HTML element can use height: 100%, however if you need the body to stretch to full height you have to use min-height: 100% instead. Otherwise the scrollTop always returns "0"
Try this, this is scroll on top with animation which is seen more effective
$("html, body").animate({ scrollTop: 0 }, 2000);
Demo Here
You use multiple selector and it will return an array of DOM elements. Calling getter function of this array seems undefined in Chrome (setter functions should work)?
Anyway you can use $('body').scrollTop() || $('html').scrollTop() in you case.
Or just $(document) as mentioned in Justin's answer.
Used this solution:
window.scrollY || window.pageYOffset || document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0)
Supplied in this answer in another thread:
https://stackoverflow.com/a/33462363
You don't need to involve jQuery and it works fine for me.
try this simple javascript code for scroll element using id
document.getElementById("id").scrollTop=0;
Remove height style from the body,html tags. Add an id to the main div under body e.g. #content then use following script. As previously quoted run $(document).scrollTop(); in the browser console and make sure it returns a value not 0.
$('body, html').animate({
scrollTop: $('#content ').offset().top
}, 1000);

Categories

Resources