I have the example code from jQuery animate
and I would like to make the div expand automatically based on a counter, based on the time, as the counter or time changes the div gets wider. I can't figure out how to use a variable to replace the width: "70%"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta name="generator" content="HTML Tidy for Windows (vers 14 February 2006), see www.w3.org">
<style type="text/css">
div {
background-color:#bca;width:100px;border:1px solid green;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript">
</script>
<title></title>
</head>
<body>
<button id="go">» Run</button>
<div id="block">
Hello!
</div>
<script type="text/javascript">
/* Using multiple unit types within one animation. */
$("#go").click(function(){ $("#block").animate({ width: "70%", opacity: 0.4, marginLeft: "0.6in", fontSize: "3em", borderWidth: "10px" }, 1500 );});
</script>
</body>
</html>
Please sample code to use a variable for width:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta name="generator" content="HTML Tidy for Windows (vers 14 February 2006), see www.w3.org">
<style type="text/css">
div {
background-color:#bca;width:100px;border:1px solid green;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript">
</script>
<title></title>
</head>
<body>
<button id="go">» Run</button>
<div id="block">
Hello!
</div>
<script type="text/javascript">
var someWidth = "70%";
/* Using multiple unit types within one animation. */
$("#go").click(function(){ $("#block").animate({ width: someWidth, opacity: 0.4, marginLeft: "0.6in", fontSize: "3em", borderWidth: "10px" }, 1500 );});
</script>
</body>
</html>
You can use relative animation by specifying += as follows
$("#go").click(function(){
$("#block").animate({
width: "+=5%",
opacity: 0.4,
marginLeft: "0.6in",
fontSize: "3em",
borderWidth: "10px"
}, 1500 );
});
This will expand div by 5% every time function is called.Adjust it fit your need.
Rather if you would like to animate on interval basis call this function in setInterval.This will call animate every 2000 milliseconds.
setInterval( function(){
$("#block").animate({
width: "+=5%",
opacity: 0.4,
marginLeft: "0.6in",
fontSize: "3em",
borderWidth: "10px"
}, 1500 );
},2000);
Related
I am learning jQuery. I made a button to show/hide a box using jQuery. It works well for the first time only. After first time it automatically showing the box after I hide it.
<!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.0" />
<title>Document</title>
<link rel="stylesheet" href="./styles.css" />
<script
src="https://code.jquery.com/jquery-1.11.3.min.js"
integrity="sha256-7LkWEzqTdpEfELxcZZlS6wAx5Ff13zZ83lYO2/ujj7g="
crossorigin="anonymous"></script>
</head>
<body>
<div class="playbox">
<div class="button"><button>Hide/Show</button></div>
<div class="box"></div>
</div>
<script src="./jQuery.js"></script>
<script>
$(".playbox").css({
width: "100%",
height: "50vh",
});
$(".button").css({
width: "50%",
height: "100%",
float: "left",
});
$("button").css({
width: "150px",
height: "100px",
});
$(".box").css({
width: "50%",
height: "100%",
background: "red",
float: "left",
});
$('button').click(function () {
$('.box').hide(2000, function () {
$('button').click(function () {
$('.box').show(2000);
});
});
});
</script>
</body>
</html>
jQuery version 1.11.3.
How can I fix it? Please help.
Every time you click the button you:
Hide the box
Add an event handler to show the box
So the second time you click the button you:
Trigger the first event handler which:
Hide the box
Add an event handler to show the box
Trigger the second event handler which:
Shows the box
Bind one event handler which behaves differently depending on if it is hidden or not.
You could write that logic yourself, but the toggle() method is already written.
Replace:
$('button').click(function () {
$('.box').hide(2000, function () {
$('button').click(function () {
$('.box').show(2000);
});
});
});
With:
$('button').on('click', () => $('.box').toggle(2000));
There is an inbuilt function in jQuery called toggle. Use it to hide/show on 1 click.
See below for example.
Thanks me later.
$(".playbox").css({
width: "100%",
height: "50vh",
});
$(".button").css({
width: "50%",
height: "100%",
float: "left",
});
$("button").css({
width: "150px",
height: "100px",
});
$(".box").css({
width: "50%",
height: "100%",
background: "red",
float: "left",
});
$('button').click(function () {
$('.box').toggle(2000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="playbox">
<div class="button"><button>Hide/Show</button></div>
<div class="box"></div>
</div>
$('button').click(function () {
$('.box').toggle(2000)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<!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.0" />
<title>Document</title>
<link rel="stylesheet" href="./styles.css" />
<script
src="https://code.jquery.com/jquery-1.11.3.min.js"
integrity="sha256-7LkWEzqTdpEfELxcZZlS6wAx5Ff13zZ83lYO2/ujj7g="
crossorigin="anonymous"></script>
</head>
<body>
<div class="playbox">
<div class="button"><button>Hide/Show</button></div>
<div class="box"></div>
</div>
<script src="./jQuery.js"></script>
<script>
$(".playbox").css({
width: "100%",
height: "50vh",
});
$(".button").css({
width: "50%",
height: "100%",
float: "left",
});
$("button").css({
width: "150px",
height: "100px",
});
$(".box").css({
width: "50%",
height: "100%",
background: "red",
float: "left",
});
</script>
</body>
</html>
you could fix that:
$('button').click(function () {
if($('.box').is(":visible")){
$('.box').hide(2000);
}else{
$('.box').show(2000);
}
});
or use toggle():
$('button').click(function () {
$('.box').toggle(2000);
});
I'm running it in vscode and when I run my site, the spot where the javascript should be, is just a blank area. I tried a console.log message to test it and that isn't coming through either.
Here's where I'm trying to add a progress bar.
<p class="infoBox">
<h3>Skills</h3>
<h4>Computer Languages</h4>
Java <div id="container"></div></br>
Python</br>
Here's my javascript.
<script type="text/javascript" src="/require.js">
console.log("Hello World!"); // a test for js and it's not showing up in chrome's console
var ProgressBar = require('progressbar.js');
var bar = new ProgressBar.Line(container, {
strokeWidth: 4,
easing: 'easeInOut',
duration: 1400,
color: '#FFEA82',
trailColor: '#eee',
trailWidth: 1,
svgStyle: {width: '100%', height: '100%'}
});
bar.animate(1.0);
</script>
Here's my css.
#container {
margin: 20px;
width: 400px;
height: 8px;
}
Here's what's coming up when I run it.
You mixed something up. if you use <script src=""></script> you tell the browser to import a js library (in your case require.js). The contents between <script> and </script> are then ignored.
If you want to execute javascript code you have two options.
Option 1: Inline Javascript like this:
<script src="require.js"></script>
<script>
console.log("test")
</script>
Option 2: Create your own .js file and extract the code there:
<script src="require.js"></script>
<script src="your_own_js_file.js"></script>
If src is in the tag it will not read its contents. Simply remove the src and it should work.
According to your source variable container is undefined, so you try to set the progress bar to an empty container. So either assign value '#container' to your variable or just replace new ProgressBar.Line(container, with new ProgressBar.Line("#container",
And yes, you need to split and your script like
<script src="/require.js"/>
<script>
Your script here
</script>
Since you are using the id of the div element to render the progress bar, you need to load the javascript code after the window is loaded.
index.js
window.onload = function onLoad() {
var bar = new ProgressBar.Line(container, {
strokeWidth: 4,
easing: 'easeInOut',
duration: 1400,
color: '#FFEA82',
trailColor: '#eee',
trailWidth: 1,
svgStyle: { width: '100%', height: '100%' },
});
bar.animate(1.0);
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>ProgressBar.js - Minimal Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
#container {
margin: 20px;
width: 400px;
height: 8px;
}
</style>
</head>
<body>
<p class="infoBox"></p>
<h3>Skills</h3>
<h4>Computer Languages</h4>
<p>Java</p>
<div id="container"></div>
<p>Python</p>
<script src="https://cdn.rawgit.com/kimmobrunfeldt/progressbar.js/0.5.6/dist/progressbar.js"></script>
<script src="index.js"></script>
</body>
</html>
I have a modal popup that opens on a button click. I am trying to dim the background when the popup open but I can't get it to work.
This is what I have:
JavaScript:
function popup(centername, centertype, area, address, province, itprovider, software, addon,
principalname, principleemmail, itname, itemail, itno, academicname, academicno, academicemail,
invigilatorname, invigilatorno, invigilatoremail, centeridep, provinceidep, centernameep, centertypeidep, id) {
var $dropdown = $("#ddlCenterType");
$("#txtCenterName").val(centername);
$("#txtArea").val(area);
$("#txtAddress").val(address);
$("#ddlProvince").val(province);
$("#ddlProvider").val(itprovider);
$("#ddlSoftware").val(software);
$("#ddlAddOn").val(addon);
$("#txtPrincipalName").val(principalname);
$("#txtPrincipalEmail").val(principleemmail);
$("#txtITName").val(itname);
$("#txtITemail").val(itemail);
$("#txtITNumber").val(itno);
$("#txtAcadName").val(academicname);
$("#txtAcadNumber").val(academicno);
$("#txtAcadEmail").val(academicemail);
$("#txtInvName").val(invigilatorname);
$("#txtInvNumber").val(invigilatorno);
$("#txtInvEmail").val(invigilatoremail);
$("#txtCenterId").val(centeridep);
$("#txtProvinceID").val(provinceidep);
$("#txtCtrName").val(centernameep);
$("#txtTypeID").val(centertypeidep);
$("#txtID").val(id);
$dropdown.val(centertype);
$("#popupdiv").dialog({
width: 1250,
height: 1290,
autoOpen: true,
modal: true,
open: function (event, ui) {
$(".ui-widget-overlay").css({
background: "rgb(0, 0, 0)",
opacity: ".50 !important",
filter: "Alpha(Opacity=50)",
});
},
buttons: {
Close: function () {
$(this).dialog("close");
}
}
});
}
I also added this in the CSS but still doesn't work:
.ui-widget-overlay {
opacity: .50 !important;
filter: Alpha(Opacity=50) !important;
background-color: rgb(50, 50, 50) !important;
}
I know this question has been asked a couple of times but I still can't get it to work. Please assist. Thanks!
Just remove the important from opacity and it will work. Though I would recommend to use CSS for this. You can add and remove a class when modal opened and closed, and use it in combination with ui-widget-overlay to override background and opacity.
Here is a working example of how would that work
$( function() {
$("#dialog").dialog({
width: 360,
height: 290,
autoOpen: true,
modal: true,
open: function (event, ui) {
$(".ui-widget-overlay").addClass('modal-opened');
},
close: function(event, ui){
$(".ui-widget-overlay").removeClass('modal-opened');
}
});
} );
.ui-widget-overlay.modal-opened{
background: rgb(0, 0, 0);
opacity: 0.5;
filter: Alpha(Opacity=50);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="script.js"></script>
</body>
</html>
Here is a plnkr of the above example https://plnkr.co/edit/GUW4NFEO9omn898n8aGm?p=preview
I have some problems with a school assignment. Anyway, when I use startInterval, I assign and intervalID so I can later clear the interval. Unfortunately, it does not clear when you press the "stop this madness" button. Anyone know why?
(if you are wondering about all the background color stuff I used a jquery plugin which I didn't add to this snippet)
var intervalID;
$('.gal').click(function() {
var photoID = jQuery(this).attr("id");
alert(alerts[photoID]);
});
var alerts = {
//row one
"1:1": "This animal is a penguin!",
"1:2": "This animal is a lion!",
"1:3": "This animal is a cat!",
"1:4": "This animal is a giraffe!",
//row two
"2:1": "Cool looking ancient building!",
"2:2": "Cool looking modern building!",
"2:3": "Cool building from dubai!",
"2:4": "Cool building by the water!"
};
$("#stop").click(function() {
clearInterval(intervalID);
});
$(window).load(function() {
animate();
});
function animate() {
intervalID = setInterval(function() {
var width = 25;
$(".gal").animate({
'marginLeft': '-=25px'
});
$(".gal").animate({
'marginLeft': '+=25px'
});
$("#title").animate({
'marginLeft': '+=' + width + 'px'
}, "slow");
$("#title").animate({
'marginLeft': '-=' + width + 'px'
}, "slow");
$("body").animate({
'backgroundColor': 'lightyellow'
}, 1000);
$("body").animate({
'backgroundColor': 'yellow'
}, 1000);
$("body").animate({
'backgroundColor': 'orange'
}, 1000);
$("body").animate({
'backgroundColor': 'red'
}, 1000);
$("body").animate({
'backgroundColor': 'lightpink'
}, 1000);
$("body").animate({
'backgroundColor': 'pink'
}, 1000);
$("body").animate({
'backgroundColor': 'purple'
}, 1000);
$("body").animate({
'backgroundColor': 'blue'
}, 1000);
$("body").animate({
'backgroundColor': 'lightblue'
}, 1000);
$("body").animate({
'backgroundColor': 'cyan'
}, 1000);
$("body").animate({
'backgroundColor': 'green'
}, 1000);
$("body").animate({
'backgroundColor': 'lightgreen'
}, 1000);
}, 0.1);
}
body {
background-color: lightyellow;
}
#title {
display: block;
/*position:absolute;*/
}
.gal {
display: block;
margin: 20px;
width: 250px;
height: 200px;
border: 5px solid black;
}
#stop {
position: fixed;
bottom: 0;
right: 0;
border: 3px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>JS Functions</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container-fluid">
<button id="stop" class="btn-warning">Stop This Madness!</button>
<h1 id="title" style="margin-left: 20px;" class="text-primary">Image Gallery:</h1>
<div class="row">
<div class="col-md-3">
<img id="1:1" src="http://ngm.nationalgeographic.com/2012/11/emperor-penguins/img/02-airborne-penguin-exits-water_1600.jpg" class="gal">
</div>
<div class="col-md-3">
<img id="1:2" src="http://efdreams.com/data_images/dreams/lion/lion-03.jpg" class="gal">
</div>
<div class="col-md-3">
<img id="1:3" src="https://s3.graphiq.com/sites/default/files/stories/t2/tiny_cat_12573_8950.jpg" class="gal" />
</div>
<div class="col-md-3">
<img id="1:4" src="https://upload.wikimedia.org/wikipedia/commons/0/02/Giraffe_Ithala_KZN_South_Africa_Luca_Galuzzi_2004.JPG" class="gal">
</div>
</div>
<div class="row">
<div class="col-md-3">
<img id="2:1" src="http://cdn.mos.cms.futurecdn.net/78b7453e70727aae7eed989ff2cee83d.jpg" class="gal" />
</div>
<div class="col-md-3">
<img id="2:2" src="http://thegrumpyoldlimey.com/images/buildings/dome_feature.jpg" class="gal" />
</div>
<div class="col-md-3">
<img id="2:3" src="https://d3dupjkkwlat3o.cloudfront.net/399433011453/2071971/576xN?1410992818" class="gal" />
</div>
<div class="col-md-3">
<img id="2:4" src="http://www.jazzhostels.com/blog/wp-content/uploads/2014/09/hemispheric-photo-valencia-spain-cc.jpg" class="gal">
</div>
</div>
</div>
<script></script>
<script src="script.js"></script>
</body>
</html>
Two general points you need to know:
The delay for setInterval() is specified in milliseconds, and you have specified a delay of 0.1 - which means you've tried to schedule your function to run 10000 times per second. In practice JS doesn't let you go under 5ms: any shorter delay specified will be rounded up, but still that means your function will run approximately 200 times per second.
When you call .animate() multiple times on the same element, as you are doing with .gal, #title, and body, it queues up additional animations that will be run after the current ones finish.
Putting those two points together, and every 5ms your code adds multiple animations to the queue, each of which takes a lot longer than 5ms. So even when you call clearInterval(), you've already got tons of animations still queued up and they will take a long time to complete.
You can stop animations currently underway and clear a given element's animation queue using the .stop() method:
$(".gal").stop(true);
But trying to manage ongoing animations using setInterval() is always going to be a bit clunky, especially where you have multiple animations with different times specified. But fortunately the .animate() method lets you provide a callback function that will run after the animation completes, so you can schedule additional processing from there.
You asked in a comment about whether there's a more efficient way to manage the animations: for all those colour changes I'd suggest using an array, then when the current colour change completes call .animate() again for the next colour in the array.
So maybe something like the following, noting that I've removed some of the code that didn't relate to the animations in order to make this answer a bit shorter, and I've split the animation code into three functions to make it clearer for you what each one is doing:
$("#stop").click(function() {
$(".gal, #title, body").stop(true);
});
$(window).load(function() {
animateGallery();
animateTitle();
animateBody();
});
function animateGallery() {
$(".gal").animate({
'marginLeft': '-=25px'
}, "slow").animate({
'marginLeft': '+=25px'
}, "slow", animateGallery); // note the function set as final argument
// - it will be called when animation finishes
}
function animateTitle() {
var width = 25;
$("#title").animate({
'marginLeft': '+=' + width + 'px'
}, "slow").animate({
'marginLeft': '-=' + width + 'px'
}, "slow", animateTitle); // note the function set as final argument
}
var colors = ['lightyellow', 'yellow', 'orange', 'red', 'lightpink', 'pink', 'purple', 'blue', 'lightblue', 'cyan', 'green', 'lightgreen'];
var currentColor = 0;
function animateBody() {
$("body").animate({
'backgroundColor': colors[currentColor]
}, 1000, animateBody); // note the function set as final argument
currentColor = (currentColor + 1) % colors.length;
}
#title { display: block; }
.gal { display: block; margin: 20px; width: 250px; height: 200px; border: 5px solid black; }
#stop { position: fixed; z-index: 100; bottom: 0; right: 0; border: 3px solid red; }
<!DOCTYPE html>
<html lang="en">
<head>
<title>JS Functions</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>
</head>
<body>
<div class="container-fluid">
<button id="stop" class="btn-warning">Stop This Madness!</button>
<h1 id="title" style="margin-left: 20px;" class="text-primary">Image Gallery:</h1>
<div class="row">
<div class="col-md-3">
<img id="2:1" src="http://cdn.mos.cms.futurecdn.net/78b7453e70727aae7eed989ff2cee83d.jpg" class="gal" />
</div>
<div class="col-md-3">
<img id="2:2" src="http://thegrumpyoldlimey.com/images/buildings/dome_feature.jpg" class="gal" />
</div>
<div class="col-md-3">
<img id="2:3" src="https://d3dupjkkwlat3o.cloudfront.net/399433011453/2071971/576xN?1410992818" class="gal" />
</div>
<div class="col-md-3">
<img id="2:4" src="http://www.jazzhostels.com/blog/wp-content/uploads/2014/09/hemispheric-photo-valencia-spain-cc.jpg" class="gal">
</div>
</div>
</div>
</body>
</html>
I have looked at other posts and there is a running solution involving "event" however I can't see how that fits into my code. As it stands the .animate() function, more specifically the duration functionality, doesn't seem to work unless I use chrome.
Here is my code.
index.html
<title>Quests Development Space</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html"; charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="css/stylesheet.css" />
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="javascript.js"></script>
<div id="circle"></div>
javascript.js
$(document).ready(function() {
$("#circle").click(function() {
$(this).animate({
borderRadius:"0px"
}, {
duration: 1600
});
});
});
I have tried iterations without the ",{duration: x}" and just ", 1500" as I have seen it used both ways however neither works in anything except Chrome.
The function turns a circle into a square and still does in all browsers however it is only animated in Chrome.
Edit:
stylesheet.css
#circle {
height: 100px;
width: 100px;
border-radius: 50px;
background-color: blue;
}
Here is the CSS for those who asked though as I said it does work just only animates on Chrome.
Edit 2:
Breaking News!
It seems it is animating however it is "blinking" to border-radius 0 then animating inwards.
Try this code snippet:
$(function() {
$("#circle").click(function() {
$(this).animate({
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
WebkitBorderTopLeftRadius: 0,
WebkitBorderTopRightRadius: 0,
WebkitBorderBottomLeftRadius: 0,
WebkitBorderBottomRightRadius: 0,
MozBorderRadius: 0
}, 1600);
});
});
You need to set all cross browser border radius properties to run it across all the browsers.
Plunker