Font increase animation doesn't work JavaScript - javascript

i am trying to recreate a simple jQuery animation with JavaScript. And it doesn't work. I would be very happy if you tell me what is wrong, because for me it seems right. Thank you in advance!
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").animate({fontSize: "100px"}, "slow");
});
</script>
</head>
<body>
<div style="background:#98bf21;height:200px;width:600px;">Hello World</div>
</body>
</html>
And below is the JavaScript animation:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>This is a title!!!</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div style="background-color: #98bf21; width: 200px; height: 600px;">Hello World!</div>
<button onclick="startFontIncrease()">Click me</button>
<script>
function startFontIncrease() {
var element = document.getElementsByTagName("div")[0];
var fontSize = element.style.fontSize;
var id = setInterval(increaseFont, 5);
function increaseFont() {
if (fontSize == 100) {
clearInterval(id);
}
else {
fontSize++;
element.style.fontSize = fontSize;
}
}
}
</script>
</body>
</html>

There are numerous problems with the transcription to plain JS.
To begin with, you have not set an initial font-size in the inline style and it is thus an empty string when you try to access it. So the HTML should be like this:
<div style="background-color: #98bf21; width: 200px; height: 300px; font-size: 12px;">
Hello World!
</div>
Then, you must get the initial font size out of the font-size increasing function and you must also parse it to make sure you get the number (and not the "12px" string, otherwise it will be NaN when you try to increment).
var element = document.getElementsByTagName("div")[0];
var fontSize = parseInt(element.style.fontSize);
function startFontIncrease() {
var id = setInterval(increaseFont, 5);
function increaseFont() {
if (fontSize == 100) {
clearInterval(id);
}
else {
fontSize++;
element.style.fontSize = fontSize + 'px';
}
}
}

Instead of giving slow attribute,adjust them in milliseconds if possible.
<script>
$(document).ready(function(){
$("div").animate({fontSize: "100px"}, 2000);
});
</script>

Your implementation doesn't work because the fontSize you get for the div is ""
What you have to is
document.getElementById("btn").addEventListener("click",startFontIncrease);
function startFontIncrease() {
var element = document.getElementsByTagName("div")[0];
var fontSize = parseFloat(window.getComputedStyle(element, null).getPropertyValue('font-size'));
var id = setInterval(increaseFont, 100);
function increaseFont() {
if (fontSize == 100) {
clearInterval(id);
} else {
fontSize++;
element.style.fontSize = fontSize + "px";
}
}
}
For the jQuery version Hameed Syed seams to be correct.

Related

Rotate image via Range Slider

Hi guys how to make the image rotate via range slider?
I built the function so it can range between 0 and 360 and show the value range, it's working fine, but how to apply this to rotate the image?
The crop image script documentation is here
I updated the code with the crop script, please help to rotate the image and output to a div
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Cropper.js</title>
<!-- <link rel="stylesheet" href="dist/cropper.css"> -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.css" />
<style>
.container {
max-width: 640px;
margin: 20px auto;
}
img {
max-width: 100%;
}
</style>
</head>
<body>
<div class="container">
<h1>Cropper with a range of aspect ratio</h1>
<div>
<img id="image" src="https://fengyuanchen.github.io/cropperjs/images/picture.jpg" alt="Picture">
</div>
<button onclick="cropper.getCroppedCanvas()">Save</button>
</div>
<!-- <script src="dist/cropper.js"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
var image = document.querySelector('#image');
var minAspectRatio = 1.0;
var maxAspectRatio = 1.0;
var cropper = new Cropper(image, {
ready: function () {
var cropper = this.cropper;
var containerData = cropper.getContainerData();
var cropBoxData = cropper.getCropBoxData();
var aspectRatio = cropBoxData.width / cropBoxData.height;
var newCropBoxWidth;
if (aspectRatio < minAspectRatio || aspectRatio > maxAspectRatio) {
newCropBoxWidth = cropBoxData.height * ((minAspectRatio + maxAspectRatio) / 2);
cropper.setCropBoxData({
left: (containerData.width - newCropBoxWidth) / 2,
width: newCropBoxWidth
});
}
},
cropmove: function () {
var cropper = this.cropper;
var cropBoxData = cropper.getCropBoxData();
var aspectRatio = cropBoxData.width / cropBoxData.height;
if (aspectRatio < minAspectRatio) {
cropper.setCropBoxData({
width: cropBoxData.height * minAspectRatio
});
} else if (aspectRatio > maxAspectRatio) {
cropper.setCropBoxData({
width: cropBoxData.height * maxAspectRatio
});
}
}
});
});
</script>
<script>
function updateTextInput(val) {
document.getElementById('textInput').value=val;
}
</script>
<input type="range" name="rangeInput" min="0" max="360" onchange="updateTextInput(this.value);">
<input type="text" id="textInput" value="">
<!-- FULL DOCUMENTATION ON https://github.com/fengyuanchen/cropperjs -->
</body>
</html>
You can use some javascript to set the rotation of the image when the slider value changes. Since you have jQuery:
$(function(){
let slider = $('input[type=range]'),
image = $('#image');
slider.on('change mousemove', function(){
image.css('transform', 'rotate(' + $(this).val() + 'deg)');
});
});
Side note: This type of event assignment - finding the element in javascript, rather than adding onchange attributes to the input - is much more flexible and maintainable.
Here's an example: https://codepen.io/benjamin-hull/pen/ewxboE
A couple of things to watch:
I've added the 'mousemove' event listener as well as 'change', so the user gets real-time feedback as they move the slider. This might be a problem, as mousemove can produce 100's of events. You might need to look at 'debouncing' that event to limit it to a sensible value.
In my example, I've set the slider to min -180, max 180 and a default of 0. This allows the user to rotate left and right.
You probably want the rotation to scale the image as well, so it always fills the frame.

How to update text in window using .innerHTML

I am making a very simple page that just counts how many seconds the user has had the tab open. In the console the seconds update, but on the page in the browser, it ain't.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Counter</title>
<script type="text/javascript">
window.seconds = document.getElementById('counts');
var count = setInterval('counter()', 1000);
function counter(){
console.log(seconds)
document.getElementById('counts').innerHTML = window.seconds + 1;
}
</script>
<style>
h2 {
text-align:center;
color:#032441;
font-family:monospace;
}
div {
text-align:center;
color:#032441;
font-size:70px;
font-family:monospace;
}
</style>
</head>
<body>
<script>
document.body.style.backgroundColor = "#EBE9BD"
</script>
<h2>
You have been on this page for
</h2>
<div id="counts">
0
</div>
<h2>
seconds.
</h2>
</body>
</html>
What is the problem?
The variable seconds is declared too soon before the element is even rendered, that's why I added the window.onload wrapper to your code.
You need to use innerHTML to change the content of a div element.
Not related, but you can also style the body tag via CSS rule.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Counter</title>
<script type="text/javascript">
window.onload = function () {
var seconds = document.getElementById('counts');
var count = setInterval(counter, 1000);
function counter(){
var newCount = Number(seconds.innerHTML) + 1
console.log(newCount);
seconds.innerHTML = newCount;
}
}
</script>
<style>
body {
backgroundColor: "#EBE9BD";
}
h2 {
text-align: center;
color: #032441;
font-family: monospace;
}
div {
text-align: center;
color: #032441;
font-size: 70px;
font-family: monospace;
}
</style>
</head>
<body>
<h2>
You have been on this page for
</h2>
<div id="counts">
0
</div>
<h2>
seconds.
</h2>
</body>
</html>
You could use the following:
<script type="text/javascript">
window.seconds = document.getElementById('counts');
setInterval('counter()', 1000);
function counter(){
console.log(seconds.innerHTML);
window.seconds.innerHTML++;
}
</script>
Bare in mind that 'counts' is not yet defined as soon as the script runs.
To access the "body" of an Element you have to access it via element.innerHTML which in your case would look like window.seconds.innerHTML = window.seconds.innerHTML + 1
EDIT: But that won't fix your problem.
Your script does not detect the <div id="counts"> element, since it has not been loaded yet, you can fix this by moving the script after the div
Since innerHTML returns a string, performing + will attach both strings and your seconds will look like 011111111 So you'll have to parse it to a string via parseInt(window.seconds.innerHTML)
So changing
window.seconds = window.seconds + 1
to
window.seconds.innerHTML = parseInt(window.seconds.innerHTML) + 1;
and moving the script tag at the very bottom, should to the trick

Toggling div-size via javascript

I'm trying to use javascript to toggle the size of a div. In order to understand the basic idea of how to do this I tried replicating this example: Toggling Div (JSFiddle)
But for some reason it is not working, despite me having copied it from the working JSFiddle. Why is that? Here is my replicate:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style type="text/css">#topbar {
background: orange;
color: white;
height: 10px;
text-align:center;
}</style>
<script type="text/javascript">
$("#topbar").click((function() {
var i = 0;
return function() {
$(this).animate({
height: (++i % 2) ? 40 : 10
}, 200);
}
})());
</script>
</head>
<body>
<div id='topbar'>toggle me</div>
</body>
</html>
Wow! You haven't added jQuery at all! Add this in your <head> before you call the script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You must have got this error in the console:
Reference Error: $ not defined.
You are using this not in context. When you put it inside a function, then it gets screwed up. Do it this way:
$(function () {
$("#topbar").click(function () {
var i = 0;
$(this).animate({
height: (++i % 2) ? 40 : 10
}, 200);
return false;
});
});
The this you used, will be taking your inner function as its context. And since your <div> comes after the <script>, please enclose it inside the $(function () {}).

Un-ending image using mouse scroll

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Frog</title>
<script type="text/javascript">
window.onscroll = infinity;
function infinity () {
document.write("<img src='frog.gif'>" + "<br/>");
}
while(window.onscroll){
infinity();
}
</script>
</head>
<body>
<img src='earth.png'>
<br/>
<img src='tiger.jpg'>
<br/>
</body>
</html>
Hi guys, I want to know how would I loop the frog when every time I scroll down the frog image appears again thanks in advance!
If you need to add image when user actually turns mouse wheel (even when no actual scrolling is involved) - you need to capture "mousewheel" event. Universally crossbrowser you can to it like this:
if (document.addEventListener) {
document.addEventListener("mousewheel", MouseWheelHandler, false);
document.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
else {
document.attachEvent("onmousewheel", MouseWheelHandler);
}
If you create a placeholder to hold your future images:
<div id="fdiv">Froggies:</div>
You can add images to it on mousewheeling like this:
function MouseWheelHandler(e) {
var e = window.event || e;
var delta = e.wheelDelta
if (delta < 0)
var img = document.createElement("img");
img.src = "frog.gif";
document.getElementById("fdiv").appendChild(img);
}
What this does is detects whether user scrolls mouse down (delta < 0) and if so - creates a new frog image and adds it to the DIV.
Here's demo: http://jsfiddle.net/Z8AxG/2/ place the mouse over window with words "Froggies:" and turn mouse wheel down.
What you could try is to make a div modify its height when you scroll down (using Javascript). Then apply the image on the background and let it repeat using CSS:
div#infinity {
background-image: url('frog.gif');
background-repeat: repeat-y;
}
With other words, this script will add images when you scroll down:
<!DOCTYPE html>
<html>
<head>
<title>TEST: Infinity Scroll</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var lastScrollTop = 0;
$(window).scroll(function(event) {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
$('div#infinity').append(
$('<div>').attr("id", "infinityimage")
);
}
else {
// upscroll code
}
lastScrollTop = st;
});
</script>
<style type="text/css">
html, body {
height: 101%;
}
div#infinityimage {
height: 190px;
background-image: url('https://www.google.nl/images/srpr/logo6w.png');
background-repeat: repeat-y;
}
</style>
</head>
<body>
<div id="infinity">
</div>
</body>
</html>

How to center text with dynamic length at a give point?

I have the following function which needs to print dynamically generated text(txt) centered at a given point(x,y)
function printText(x,y,txt) {
var s = "";
s = "<b style=???>"+txt+"</b>";
document.getElementById("some_div").innerHTML = s;
}
How can I do this?
Make the position of the div relative and use absolute positioning on the inner element, something like this:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>Test</title>
<meta charset="UTF-8" />
<style>
#some_div {
postion:relative;
height:300px;
}
#some_div b {
position:absolute;
}
</style>
<script>
function printText(x, y, txt) {
var s = "<b style=\"left:" + x + "px;top:" + y + "px;\">"+txt+"</b>";
document.getElementById("some_div").innerHTML = s;
}
</script>
</head>
<body>
<div id="some_div"></div>
<button onclick="printText(100, 40, 'This is a test');">Click Me</button>
</body>
</html>

Categories