appendTo is not working with each in jquery - javascript

I have to apply animation on each "div". But it is applying just in first one not in all.
According to me "$("#viewport").each(appendTo(c));" this line is not working in javascript code.
HTML code:
<div id="viewport"></div>
<div id="viewport"></div>
<div id="viewport"></div>
Javascript code:
$(window).load(function(){
$(function () {
var a = 0;
for (; a < 15; a += 1) {
setTimeout(function b() {
var a = Math.random() * 1e3 + 5e3,
c = $("<div />", {
"class": "smoke",
css: {
opacity: 0,
left: Math.random() * 200 + 80
}
});
**$("#viewport").each(appendTo(c));**
$.when($(c).animate({
opacity: 1
}, {
duration: a / 4,
easing: "linear",
queue: false,
complete: function () {
$(c).animate({
opacity: 0
}, {
duration: a / 3,
easing: "linear",
queue: false
})
}
}), $(c).animate({
bottom: $("#viewport").height()
}, {
duration: a,
easing: "linear",
queue: false
})).then(function () {
$(c).remove();
b()
});
}, Math.random() * 3e3)
}
}());
});

Use more than one element with the same id is absolutely bad practice! Put "vieport" as class and use
$( ".viewport" )
The .each() function take a function as first argument and in that function context, the "this" variable will contain the element
$( ".viewport" ).each( function() {
$( this ).appendTo( c );
});

If I am not wrong. You want something like this:
HTML:
<div id="viewport">
<div class="smoke smoke1"></div>
<div class="smoke smoke2"></div>
<div class="smoke smoke3"></div>
</div>
JS:
(function () {
"use strict";
$('#viewport .smoke').each(function ns () {
var initialTop = $(this).position().top;
$(this).animate({
top: - $(this).height()
}, Math.random() * 2000 + 2000, function () {
$(this).css({
top: initialTop,
opacity: 0
});
}).animate({
opacity: 1
}, ns)
});
}());
CSS:
#viewport {
position: relative;
width: 400px;
height: 300px;
margin: 100px auto;
border: 1px solid #333333;
overflow: hidden;
}
#viewport .smoke {
position: absolute;
width: 20px;
height: 40px;
background: rgba(0, 0, 0, 0.5);
}
#viewport .smoke1 {
left: 140px;
top: 260px;
}
#viewport .smoke2 {
left: 180px;
top: 260px;
}
#viewport .smoke3 {
left: 220px;
top: 260px;
}
Please see demo here: http://jsfiddle.net/1rf31eyL/
You may check another example demo here: http://gettycreations.com/

first of all
add function in $.each
like
"$("#viewport").each(
function(){
$(this).appendTo(c);
}
);
and then try this,
$("[id=viewport]")
When you use
$("#viewport")
it selects only the first element with the given ID.
However, when you select by attribute (e.g. id in your case), it returns all matching elements, like so:
$("[id=viewport]")

Related

Using append to create an overlay in a jQuery plugin

I am trying to make a small jQuery plugin that is able to create an overlay to create a tinting effect. To create this overlay is simple enough using plain js & jQuery, but when I try to wrap it all up into a jQuery plugin I get the error message that append (and appendTo) are not functions. The plugin works if I use extend instead of append, but the it is simply changing the existing css code, while I want to create an actual overlay over any div or object.
(function ($) {
$.fn.tint = function( options )
{
var overlay = $.append(
{
backgroundColor: "black",
opacity: 0.5,
width: "100%",
height: "100%",
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
//"z-index": 1000,
}, options
);
return this.css(
{
backgroundColor: overlay.backgroundColor,
opacity: overlay.opacity,
width: overlay.width,
height: overlay.height,
position: overlay.position,
top: overlay.top,
left: overlay.left,
right: overlay.right,
bottom: overlay.bottom,
//z-index: overlay.z-index,
}
);
}
} ( jQuery ));
I guess you are trying to do $.extend (not $.append):
(function ($) {
$.fn.tint = function( options )
{
if($(this).find(".overlay").length > 0) return $(this);
var overlay = $.extend({
backgroundColor: "black",
opacity: 0.5,
width: "100%",
height: "100%",
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
//"z-index": 1000,
}, options);
$("<div class='overlay'>").css(
{
backgroundColor: overlay.backgroundColor,
opacity: overlay.opacity,
width: overlay.width,
height: overlay.height,
position: overlay.position,
top: overlay.top,
left: overlay.left,
right: overlay.right,
bottom: overlay.bottom,
//z-index: overlay.z-index,
}
).appendTo(this);
return $(this);
}
} ( jQuery ));
$(".overlay-target").on("click", function(){
$(this).tint({backgroundColor: "green"});
});
.overlay-target {
border: 1px solid red;
margin: 20px;
padding: 50px;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='overlay-target'>I want an overlay</div>

Change element size jQuery

I want to change element size by animate function. But when I do this, all my page elements are slide down. Is there any existing way to avoid sliding down elements of page?
My code:
$(".animated_blue_1").delay(800).animate({
"height":230,
"width":230
},500, function () {
$(".animated_blue_1").animate({
"height":200,
"width":200
},500);
});
If you have elements arranged like this:
+---+
| A |
+---+
+---+
| B |
+---+
...and you make A taller, what do you expect to happen to B? It needs to move down to make room, barring you telling it to do something else.
You could tell it to stay put by using absolute positioning:
var b = $("B"); // Obviously make the selector something real
var pos = b.position();
b.css({
position: "absolute",
left: pos.left,
top: pos.top
});
...but then of course A and B would overlap.
Option A: They move down:
var run = true;
$("input[type=button]").click(function() {
run = false;
});
go();
function go() {
$(".foo").animate({
width: 130,
height: 130
}, 500).promise().then(function() {
$(".foo").animate({
width: 100,
height: 100
}, 500).promise().then(function() {
if (run) {
setTimeout(go, 200);
}
});
});
}
.foo {
width: 100px;
height: 100px;
border: 1px solid black;
}
#a {
background-color: #ee0;
}
<input type="button" value="Stop">
<div id="a" class="foo">A</div>
<div id="b" class="foo">B</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Option B: They overlap:
var run = true;
$("input[type=button]").click(function() {
run = false;
});
var b = $("#b");
var pos = b.position();
b.css({
position: "absolute",
left: pos.left,
top: pos.top
});
go();
function go() {
$(".foo").animate({
width: 130,
height: 130
}, 500).promise().then(function() {
$(".foo").animate({
width: 100,
height: 100
}, 500).promise().then(function() {
if (run) {
setTimeout(go, 200);
}
});
});
}
.foo {
width: 100px;
height: 100px;
border: 1px solid black;
}
#a {
background-color: #ee0;
}
<input type="button" value="Stop">
<div id="a" class="foo">A</div>
<div id="b" class="foo">B</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
It means your selector is not specific to select that particular element. Check out which other elements have this animated_blue_1 class. Try to provide an ID to the element so that you can use ID instead of Class to be more specific.
If that is not the case you have to absolutely position your element, see TJ's answer.

Count back percentage using JQuery

I have the code below where I'd like to the numbers count back to 0% once hover the object out. Also I can't figure our how to make the value disappear again as it was on load. Could you please help me solve this.
Thanks in advance.
HTML
<div class="container">
<div class="fill" data-width="80%"></div>
</div>
<div class="container">
<div class="fill" data-width="50%"></div>
</div>
CSS
.container {
position: relative;
width: 300px;
height: 30px;
background-color: blue;
margin: 10px auto;
}
.fill {
height: 100%;
width: 0;
background-color: red;
line-height: 30px;
text-align: left;
z-index: 1;
text-align: right;
}
JQuery
$(function() {
$('.container').hover( function(){
var width=$(this).find(".fill").data('width');
$(this).find(".fill").animate({ width: width }, {
duration:800,
step: function(now, fx) {
$(this).html(Math.round(now) + '%');
}
});
},
function(){
$(this).find(".fill").animate({ "width": "0px" }, 800);
});
});
jsFiddle http://jsfiddle.net/zp8pe069/
jsBin demo
CSS: set overflow: hidden to .fill to prevent the text being visible after the animation ends.
HTML: remove % from the data attribute
JS and here you go. all you need:
$('.container').hover(function( e ){
var $fill = $(this).find(".fill");
var width = $fill.data('width');
$fill.stop().animate({width: e.type=="mouseenter" ? width+"%" : "0%" }, {
duration : 800,
step : function(now) {
$(this).html(Math.round(now) + '%') ;
}
});
});
Note also the use of the .stop() method, if you hover multiple time hysterically :) it'll prevent endless animations.

Adding DIVs step-by-step...1, 2, 3, 4, 8, 16

I'm trying to create div boxes step by step and animate them for several times when a button is pressed. I have a running code, and everything is going well. It goes right to the endhost, then it goes left again to its original place. This is mainly what I do, and also the demo is found here: http://jsfiddle.net/LSegC/1/
Now what I want to do is to increase the number of whole animated DIVs one-by-one (as it is now) up to 3 Divs, but then have exponential increase on the total number of DIVs. So the total number of animated DIVs will be like 1, 2, 3, and then 4, 8, 16, etc.
Remember, my problem is not with the number being shown inside the DIV, it's actually that how many DIVS are being created! So I want for instance 8 DIVs, numbered from 1 to 8 animated. Hope it is now clear.
$(document).ready(function(){
$("button").click(function() {
var d = $(".t").fadeIn();
var speed = +$("#number1").val();
d.animate({left:'+=230px'}, speed);
d.animate({left:'+=230px'}, speed);
d.animate({top:'+=20px', backgroundColor: "#f09090", text:'12'}, speed/4, "swing", function() {
$('.span', this).fadeOut(100, function() {
$(this).text(function() {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
d.delay(1000).animate({left:'-=230px'}, speed);
d.animate({left:'-=230px'}, speed);
d.fadeOut().promise().done(function() {
d.last().after(function() {
var top = +$(this).css('top').replace('px', ''),
number = +$(this).data('number') + 1,
$clone = $(this).clone();
$clone.data('number', number).css('top', top + 20);
$clone.find('.span').text(number);
return $clone;
});
d.find('.span').text(function() {
return $(this).text().replace('a', '');
});
})
});
EDIT
Your code was too hard to manipulate as it was, I recreated the whole thing:
HTML:
<img id="streamline1" src="https://cdn3.iconfinder.com/data/icons/streamline-icon-set-free-pack/48/Streamline-04-48.png" />
<img id="LAN" src="https://cdn1.iconfinder.com/data/icons/ecqlipse2/NETWORK%20-%20LAN.png" />
<img src="https://cdn3.iconfinder.com/data/icons/streamline-icon-set-free-pack/48/Streamline-04-48.png" id="streamline" />
<div id="mid"></div>
<div id="bottom"></div>
<div>Speed (mS):
<input value="500" id="speed" type="number" style="position: relative"></input>
<button>Apply!</button>
<!-- dynamic area -->
<div class="packets"></div>
</div>
JS:
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
$("button").click(function () {
if (count < 4) {
items = items + 1;
count++;
} else {
items = items * 2;
}
speed = $("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + packetNumber + "</font>").appendTo(div);
packetNumber++;
div.css("left",left+"px");
div.hide();
left += 20;
}
}
function animateDivs() {
$(".t").each(function () {
var packet = $(this);
packet.show();
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
top: '+=20px',
backgroundColor: "#f09090",
text: '12'
}, speed / 4, "swing", function () {
$('.span').fadeOut(100, function () {
$(this).text(function () {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
packet.delay(1000).animate({left:'-=230px'}, speed);
packet.animate({left:'-=230px'}, speed);
}).promise().done(function(){
$(".packets").empty();});
}
});
CSS:
#bottom {
border: 1px dashed gray;
position: absolute;
left: 55px;
height: 20px;
width: 500px;
opacity: 0.5;
top: 30px;
z-index=-1;
}
#mid {
border: 1px dashed gray;
position: absolute;
left: 55px;
height: 20px;
width: 500px;
opacity: 0.5;
top: 10px;
z-index=-1;
}
.t {
display: inline-block;
position: absolute;
top: 10px;
left: 60px;
text-align: center;
vertical-align: middle;
width: 20px;
height: 20px;
background-color: lightgreen
}
#streamline {
width: 50px;
height: 50px;
right: 0px;
position: fixed;
left: 548px;
}
#streamline1 {
left: 0px;
width: 50px;
height: 50px;
}
#LAN {
width: 50px;
height: 50px;
left: 275px;
position: fixed;
}
.packets {
display: inline;
}
FIDDLE: http://jsfiddle.net/54hqm/3/
It was tough for me to follow the code also, but I cut it back quite a bit, came up with a "one-way" "empiric" approach. FIDDLE
The speed can be adjusted by the change in the increment (inc), but there are a variety of methods that can be used.
Can you be more specific about what you mean by "exponential"? Do you mean an exponential speed increase across the div, or rather a speed increase until you get to 50%, then a decrement in speed.
JS
$("button").click(function() {
var speed = 1000;
var d = $('.mover');
d.show();
var inc = 1;
for (var i=0; i<290; i=i+inc)
{
d.animate({ left: i,
easing: 'linear'}, 1);
if (inc < 11)
{
inc = inc + 1;
} else {
inc = inc - 1;
}
}
});

Audio and animation in sync in javasctipt loop

I'm using my limited javascript skills to try an piece togheter a script that can play a small animation and a sound clip in a loop. This is what i've got so far:
<script>
function PulseArea() {
$('.area-pulse').stop();
$('.area-pulse').css({ width: 38, height: 38, top: 217, left: 77, opacity: 1 });
$('.area-pulse').animate({ width: 700, height: 700, top: -114, left: -254, opacity:0 }, 4000, null, function () { setTimeout("PulseArea()", 400); });
}
$(function() {
var sample = new Audio("audio/water-droplet-1.wav");
function playSample() {
sample.pause();
sample.currentTime = 0;
sample.play();
}
})
$(document).ready(function() {
for (i=0;i<=5;i++)
{
PulseArea();
playSample();
}
})
</script>
Related css:
.area-pulse
{
display:block;
width:38px;
height:38px;
position:absolute;
top:217px;
left:77px;
background-color:transparent;
zoom: 1;
}
.area-pulse img
{
opacity:1;
width:100%;
height:100%;
display:inline-block;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/area_pulse.png', sizingMethod='scale');
background-color:transparent;
}
Related HTML:
<div style=" width:954px; height:600px; position:absolute;" class="area-pulse"><img src="img/area_pulse.png" /></div>
It's the sound that is the problem. The animation plays fine. Any suggestions? I've searched StackOverflow, but can't find anything like this.
Thanks for taking an interest!
Your function playSample is defined inside of anonymous function scope, so it can't be called from the document.ready scope. If you move all of it into the same scope, it will work fine:
$(document.ready(function () {
function PulseArea() {
$('.area-pulse').stop();
$('.area-pulse').css({ width: 38, height: 38, top: 217, left: 77, opacity: 1 });
$('.area-pulse').animate({ width: 700, height: 700, top: -114, left: -254, opacity:0 }, 4000, null, function () { setTimeout("PulseArea()", 400); });
}
var sample = new Audio("audio/water-droplet-1.wav");
function playSample() {
sample.pause();
sample.currentTime = 0;
sample.play();
}
for (i=0;i<=5;i++) {
PulseArea();
playSample();
}
});
I don't know what was wrong with the script in my question, but i solved it by rewriting it. I hope someone else can be helped by this. :)
<script>
function PulseArea() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'audio/waterdrop.mp3');
audioElement.play();
$('.area-pulse').stop();
$('.area-pulse').css({ width: 16, height: 16, top: 227, left: 89, opacity: 1 });
$('.area-pulse').animate({ width: 700, height: 700, top: -114, left: -254, opacity:0 }, 4000, null, function () { setTimeout("PulseArea()", 400); });
}
$(document).ready(function() {
for (i=0;i<=5;i++)
{
PulseArea();
}
})
</script>

Categories