var text = document.querySelector('p')
for(var i=10px; i<=40px; i++)
text.style.fontSize = i;
I want a script which increases the font size in every iteration of the for-loop. The above code is the prototype of my requirement (which won't work since pixels can't be assigned to a variable). Help me providing the correct code.
You probably want to use setTimeout recursion instead, so the text doesn't increase in size instantly:
var text = document.querySelector('p');
function increaseTextSize(size) {
text.style.fontSize = size + 'px';
if (size <= 40) setTimeout(increaseTextSize, 50, size + 1);
}
increaseTextSize(10);
<p>my text</p>
You can also try out this demo using CSS transition effect:
// After 500ms change the font from 10 to 60px
// and css will take care of the rest
setTimeout(() => {
var text = document.querySelector('p');
text.style.fontSize = '60px';
text.style.color = 'blue'; // <-- you can also add color effects, if you want
}, 500);
p {
font-size: 10px;
color: red;
-webkit-transition: all 2.5s ease;
-moz-transition: all 2.5s ease;
-o-transition: all 2.5s ease;
-ms-transition: all 2.5s ease;
}
<p>Hello World!</p>
var text = document.querySelector('p')
for (var i = 10; i <= 40; i++) {
text.style.fontSize = `${i}px`;
}
You cannot append px in the loop since it has to be an integer.
Related
I have a simple JS script which listens to keyboard input and displays, at a random position, a short animation of every typed letter fading out and getting smaller.
'use strict'
const body = document.querySelector('body')
const ignoreKeys = [
'Alt', 'Shift', 'Control', 'CapsLock', 'Tab', 'Backspace', 'Escape', 'Meta',
'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'
]
document.addEventListener('keydown', function(e) {
if (!ignoreKeys.includes(e.key)) {
// Values 400 & 200 keep the div completely inside the window
const maxHeight = window.innerHeight - 400
const maxWidth = window.innerWidth - 200
const div = document.createElement('div')
div.className = 'anim'
div.textContent = e.key
div.style.top = getRandomInt(0, maxHeight) + 'px'
div.style.left = getRandomInt(0, maxWidth) + 'px'
body.append(div)
setTimeout(function() { div.remove() }, 3000)
}
})
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min) + min)
}
.anim {
position: fixed;
text-align: center;
animation-name: fade;
animation-duration: 2s;
animation-timing-function: ease-in-out;
opacity: 0%;
}
#keyframes fade {
0% { opacity: 100%; font-size: 300px;}
100% { opacity: 0%; font-size: 100px;}
}
By animating the font-size property, each letter gets smaller. However, since its "anchor point" is the top of the div, the visible effect is a letter getting smaller and moving slightly upwards. I would like each letter to shrink towards the vertical center of the div instead.
I can calculate the center the div easily and add the proper top coordinate to the #keyframe property, but I don't know how to modify that property in JS, individually for each div. Is this possible at all via CSS? Or should I rewrite the whole thing in pure JS?
You don't need to adjust the div's top value at all. As there is no border or anything else displayed for the DIV tag itself - just the letter within it - you can adjust either the margin, the border and/or the padding to achieve the same effect as increasing the top value for the DIV. As each of these can be handled within the css transition, you could do something like:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min) + min)
}
document.addEventListener('keydown', function(e) {
const body = document.querySelector('body')
const ignoreKeys = [
'Alt', 'Shift', 'Control', 'CapsLock', 'Tab', 'Backspace', 'Escape', 'Meta',
'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'
]
if (!ignoreKeys.includes(e.key)) {
// Values 400 & 200 keep the div completely inside the window
const maxHeight = window.innerHeight - 400
const maxWidth = window.innerWidth - 200
const div = document.createElement('div')
div.className = 'anim'
div.textContent = e.key;
div.style.top = getRandomInt(0, maxHeight) + 'px'
div.style.left = getRandomInt(0, maxWidth) + 'px'
body.append(div)
setTimeout(function() { div.remove() }, 3000)
}
})
.anim {
display:block;
position: fixed;
text-align: center;
width:200px;
animation-name: fade;
animation-duration: 2s;
animation-timing-function: ease-in-out;
opacity: 0;
margin:0px;
}
#keyframes fade {
0% { opacity:1; font-size: 300px;}
100% { opacity:0; font-size: 100px; margin-top:100px;}
}
The initial state of the DIV is with margin:0px. Adding a margin-top setting to the keyframes css, increases this from 0 to 100 during the transition. The effect of that is to push the DIV down - and, as noted above, as nothing is being displayed for the DIV itself, the user will not see it move. Note that I have fixed the width of the DIV at 200px so ensure that everything is always centered horizontally - otherwise the DIV width is based on the width of the character, so would change during transition and the character would move to the left as the centre line changes. I've moved some of the code around to make it easier to test - but the only actual change is in the CSS styling. Also note that opacity is a value from 0 to 1, so should not be shown as a percentage.
UPDATE
Have a look at the following snippet. I think that it may be possible to have random font sizes AND random positions using transform rather than animate.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min) + min)
}
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");
function zoomOUT(){
let d = document.getElementById("test");
d.classList.remove("zoomIN");
d.classList.add("zoomOUT");
}
function zoomIN(){
let d = document.getElementById("test");
let dletter = document.getElementById("testletter");
let t = getRandomInt(20, 60) * 10;
let l = getRandomInt(20, 100) * 10;
let fs = getRandomInt(10, 20) * 10;
dletter.innerHTML = letters[getRandomInt(0, 61)];
d.style.top = t + "px";
d.style.left = l + "px";
d.style.fontSize = fs + "%";
d.classList.remove("zoomOUT");
d.classList.add("zoomIN");
}
#test {
position:absolute;
padding: 50px;
margin: 0 auto;
text-align:center;
vertical-align:middle;
}
.zoomIN {
opacity:1;
transform: scale(3);
transition: transform 2s;
}
.zoomOUT {
opacity:0.5;
transform: scale(0.1);
transition: transform 3s;
}
<button onclick="zoomOUT();" z-index=1>Play</button><button onclick="zoomIN();" z-index=1>Restart</button>
<div id="test" class="zoomIN" style="top:300px; left:300px;" z-index=0><div id="testletter" style="font-size:600%; width:100%; height:100%">A</div></div>
Transform seems to keep things in the same place, so there is no need to adjust any top/margin/border/padding settings at all. In fact, the only things that change are the font-size (using scale(..)) and opacity. The size of the font is determined by the code. Note that this requires the character to be in a div within a div. This is just a test, but should give you enough to convert things into your code requirements.
I am new to Javascript. I want to make my image gradually get smaller, and then resize back to its original size. What I have works, but only after hovering over the image 2 times or more.
To be clearer, when I hover my mouse over the image for the first time, it makes a very abrupt transition, but works after that. It did the same thing when using CSS instead.
What I have is this:
function enlargeImage() {
var logo = document.getElementById('logoname');
logo.style.opacity = '0.7';
logo.style.height = 'auto';
logo.style.width = '800px';
logo.style.transition = '0.7s';
}
function resizeImage() {
var logo = document.getElementById('logoname');
logo.style.opacity = '1';
logo.style.height = 'auto';
logo.style.width = '900px';
}
Should this work? Or have I coded in a way in which I shouldn't have?
Personally I like to leave animations and effects like these to CSS and leave the functionality to Javascript.
#yourImage {
width: 150px;
height: 150px;
transition: transform .25s ease, opacity .5s ease;
}
#yourImage:hover {
opacity: 0.5;
transform: scale(0.5);
}
<img src="http://www.w3schools.com/css/trolltunga.jpg" alt="" id="yourImage">
When the image is hovered over I transform and resize the image to 0.5% of it's original size and 0.5% of it's original opacity.
I am also using the transition property to set how fast the image transitions when it is resized or when the opacity is changed.
The abruption was because of the height tag inside javascript code. change this
height: auto
Into height:400px or some value instead of auto.
function enlargeImage() {
var logo = document.getElementById('logoname');
logo.style.opacity = '0.7';
logo.style.height = '300px';
logo.style.width = '400px';
logo.style.transition = '0.7s';
}
function resizeImage() {
var logo = document.getElementById('logoname');
logo.style.opacity = '1';
logo.style.height = '600px';
logo.style.width = '600px';
logo.style.transition = '0.7s';
}
img {
height:300px;
width:400px;
}
<img onmouseover="resizeImage()" onmouseout="enlargeImage()" src='http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/sample1_l.jpg' id="logoname">
I have these buttons in html:
Home
About Me
Portofolio
As you see, these buttons call functions
functions:
<script>
function slideHome(el){
var elem = document.getElementById(el);
elem.style.transition = "left 0.5s ease-in-out 0s";
elem.style.left = "0px";
}
function slideAbout(el){
var elem = document.getElementById(el);
elem.style.transition = "left 0.5s ease-in-out 0s";
elem.style.left = "1100px";
}
these 2 work perfectly fine, but now the last function:
function slidePorto(el){
var elem = document.getElementById(el);
elem.style.transition = "top 0.5s ease-in-out 0s";
elem.style.top = "-400px";
elem.style.transition = "left 0.5s ease-in-out 1s";
elem.style.left = "1300px";
}
</script>
This function needs to move down and to the left, as a result, the "slideHome" function get's a extra line of code to move it back as well.
The problem is, that in the "slidePorto"function, it skips the first transition, it moves, but not smoothly, so it quickly moves to the bottum, and then the transition to the left fires. Same problem for the "slideHome" function when I want to move back to top:0px;
How do I get these to transitions together? Thanks in advance!
You can specify multiple transitions on an element before trigerring them by the script.
This code specifies the transitions, then do the "top" part and after that ended the transition by the "left" transition part.
function slidePorto(el) {
var elem = document.getElementById(el);
elem.style.transition = "top 0.5s ease-in-out 0s,left 0.5s ease-in-out 1s";
elem.style.top = "-400px";
elem.style.left = "1300px";
}
NB: I don't understand why you specify -400px, but it works for every value you desire.
I'm trying to alter the padding of an element based on the scroll position of the page; as the user scrolls further down the page, the padding increases, and as they scroll back up, the padding decreases.
My main problem is that the scrolling isn't very smooth, and occasionally if I scroll to the top of the page too fast, the padding of the element is a different size each time. My goal is to set a minimum and maximum amount of padding, so the scrolling is essentially a transition between two sizes. Can anyone see where I'm going wrong?
Here's my jQuery so far:
$(window).scroll(function(){
var h = 45;
if($(window).scrollTop() < 200){
$(".header").css({
'paddingTop': h-$(window).scrollTop() + "px",
'paddingBottom': h-$(window).scrollTop() + "px"
});
}
});
And here's my jsfiddle: http://jsfiddle.net/JDE8h/3/
Here you go:
JavaScript:
var _window = $(window),
header = $('.header'),
max = 50,
padding = parseFloat(header.css('padding-top')),
currentPadding = padding,
scrollPos = _window.scrollTop();
_window.scroll(function() {
if (scrollPos < _window.scrollTop() && currentPadding < max) {
header.css('padding', ++currentPadding + 'px 0');
} else if (scrollPos > _window.scrollTop() && currentPadding > padding) {
header.css('padding', --currentPadding + 'px 0');
}
if (_window.scrollTop() == 0)
header.css('padding', padding + 'px 0');
scrollPos = _window.scrollTop();
});
And add CSS transition property to .header:
.header{
/* other CSS declarations ...*/
-webkit-transition: padding .3s linear;
-moz-transition: padding .3s linear;
-ms-transition: padding .3s linear;
-o-transition: padding .3s linear;
transition: padding .3s linear;
}
JSFiddle Demo.
I believe you've got the numbers backwards. You are getting a negative number from your calculation. For example:
if h = 45, then 45 - $scrollTop (from your active target of 20 to 200) is very quickly a negative number.
Based on the example of the Carrera World website, I think believe is the effect you are looking for?
jQuery
$(window).scroll(function(){
var h = 45;
var $scrollTop = $(window).scrollTop();
if($scrollTop < 200 && $scrollTop > 20){
$(".header").css({
'paddingTop': $scrollTop - h + "px"; // Subtract h from scrollTop
'paddingBottom': $scrollTop - h + "px";
});
}
$('.header').text($scrollTop); // Display scrollTop value in header (for demo).
});
I also gave your header a min-height to keep it from getting too small in edge cases.
CSS
.header {
...
line-height: 40px; /** Keep things centered vertically **/
min-height: 40px;
}
Hopefully this helps you!
JSFiddle example.
You could use a library dedicated to this task, such as skrollr. It may not be worth it though if it's just the padding.
<div data-0="padding:0px;" data-200="padding:500px;"></div>
Will animate the padding from 0 to 500 pixels while scrolling from 0 to 200.
Here's a fiddle http://jsfiddle.net/JDE8h/9/
I want to change image with opacity transition in response to an onClick event using CSS3 without using of any javascript framework.
Here is my code which change the image but without opacity transition.
#cf img.imgClass {
-webkit-transition: opacity 2s ease-in-out;
-moz-transition: opacity 2s ease-in-out;
-o-transition: opacity 2s ease-in-out;
-ms-transition: opacity 2s ease-in-out;
transition: opacity 2s ease-in-out;
}
<_div id="cf">
<_img id='imgId' src='photos/IMG_0290.JPG'>
</_div>
(function ( ) {
document.getElementsByTagName('img')[0].onclick = function () {
return function () {
var imgSrc = document.getElementById('imgId').src;
(imgSrc.indexOf('IMG_0288.JPG') > 0) ? imgSrc = 'photos/IMG_0290.JPG' : imgSrc = 'photos/IMG_0288.JPG';
document.getElementById('imgId').src = imgSrc;
document.getElementById('imgId').className = "imgClass";
}
}();
}());
By using the following javascript function it works,
but it will be possibile just using css?
If yes, how?
function fade (id) {
var dom = document.getElementById(id),
level =1,
step = function (){
var h = level.toString(10);
dom.style.opacity = h / 10;
if (level < 10) {
level += 1;
setTimeout(step, 100);
}
}
step();
}
fade('cf');
How about this:
#cf img.imgClass {opacity on css}
#cf img.imgClass:hover {opacity off css}