Pass paramaters to animate jquery function - javascript

I would like to pass paramaters in a custom function to animate specific parts. entirely not sure what im missing?
I've created a JsFiddle
function animate($class,$method,$value,$duration,$delay) {
var delay_time = 0;
$($class).each(function() {
$(this).delay(delay_time).animate({
$method : $value
}, {
duration: $duration
});
delay_time += $delay;
});
}
animate(".container","width", 100, 300, 250);
The $method is what im trying to pass, which for some reason just doesnt want to work? What am i missing?

Working Fiddle
You couldn't define an object as you do in {$method: $value}, But you could construct you object outside of animate method then just pass it :
var my_object = {};
my_object[$method]=$value;
$(this).delay(delay_time).animate(my_object,{duration: $duration});
Hope this helps.
function animate($class,$method,$value,$duration,$delay) {
var delay_time = 0;
$($class).each(function() {
var my_object = {};
my_object[$method]=$value;
$(this).delay(delay_time).animate(my_object,{duration: $duration});
delay_time += $delay;
});
}
animate(".container","width", 100, 300, 250);
.container {
opacity: 1;
width: 0;
background: #0f0;
height: 100px;
}
p {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<p>show me</p>
</div>
<div class="container">
<p>show me</p>
</div>

Related

trying to understand function construction

I am trying to understand function construction so I can cut down on my repeated code. All the snippets I have see deal with returning values and was hoping someone could shed some light on why this doesn't work.
<div id = 'box1' style = 'background-color: green; height: 100px; width: 50px' >
</div>
var box = $('#box1');
function pushCard(x){
if(x.style.opacity == 0.5){
x.style.opacity = 1;
}
else {
x.style.opacity = 0.5;
}
}
box.click(pushCard(box));
You don't want to call the function as you pass it. You can just pass the function, then when you click it will pass the event. The element is the event target
var box = $('#box1');
function pushCard(event) {
let x = event.target
if (x.style.opacity == 0.5) {
x.style.opacity = 1;
} else {
x.style.opacity = 0.5;
}
}
box.click(pushCard);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='box1' style='background-color: green; height: 100px; width: 50px'>
</div>
You can also use this to get the clicked object:
var box = $('#box1');
function pushCard() {
if (this.style.opacity == 0.5) {
this.style.opacity = 1;
} else {
this.style.opacity = 0.5;
}
}
box.click(pushCard);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='box1' style='background-color: green; height: 100px; width: 50px'>
</div>

How to make two progress bars onload

I want to make two progress bars working on load. But the code which I write makes only one loading. Also those two progress bars has to be different in length when loaded. I don't want to repeat code, so I am adding arrays. But I am not quite sure that this is the best solution. Maybe in body tag it is possible to write two different functions, or only one can be onload? If it is possible with several functions onload, then the number array shouldnt't be used. My code below. Maybe anyone knows the solution?
<style>
.myProgress {
width: 100%;
background-color: #000000;
}
#myBar1, #myBar2 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
</style>
<body onload="move()">
<div class="myProgress">
<div id="myBar1"></div>
</div>
<div class="myProgress">
<div id="myBar2"></div>
</div>
<script>
function move() {
var ids = ["myBar1", "myBar2"];
var number = [60, 90]
var length = ids.length;
for(i = 1; i<=length; i++){
var elem = document.getElementById("myBar"+i);
var width = 1;
var id = setInterval(frame, 10);
function frame() {
if (width >= number[i-1]) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
}
</script>
The problem was caused because you were mixing loops with async operations which usually doesn't turn out well. If you want to do that you should use let instead of var or do the operation in another function. Moreover you can set the width in the html element and read all the progress bars.
function move() {
for (var item of document.querySelectorAll(".myProgress")) {
loading(item.firstElementChild, +item.getAttribute("width") || 100); // replace 100 with default
}
}
function loading(bar, maxWidth) {
var width = 0;
var intervalId = setInterval(function() {
if (width >= maxWidth) clearInterval(intervalId);
else bar.style.width = ++width + '%';
}, 10);
}
.myProgress {
width: 100%;
background-color: #000000;
}
#myBar1,
#myBar2 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
<body onload="move()">
<div class="myProgress" width="60">
<div id="myBar1"></div>
</div>
<div class="myProgress" width="90">
<div id="myBar2"></div>
</div>
</body>

How to fill text with particles using p5js

I want to fill a text with particles like this
I tried to do this using p5.js but I am stuck where the particles are only appearing on the edges. Any idea to accomplish this rather than having it on the edges?
Here is my attempt.
Thanks a ton in advance :)
SteeringDemo.html
<body>
<script>
var font;
var vehicles=[];
var x=1360;
var y=400;
function preload() {
font=loadFont('Poppins-Medium.ttf')
}
function setup() {
var canvasDiv = document.getElementById('canvas');
var width = canvasDiv.offsetWidth;
var sketchCanvas = createCanvas(width,450);
console.log(sketchCanvas);
sketchCanvas.parent("canvas");
background('#fff');
var points=font.textToPoints('B',x/3,y/2,240);
console.log(points);
for(i=0;i<points.length;i++){
var pt=points[i];
var vehicle = new Vehicle(pt.x, pt.y);
vehicles.push(vehicle);
}
}
function draw() {
background('#fff');
for(var i=0; i< vehicles.length;i++){
var v=vehicles[i];
v.behaviors();
v.update();
v.show();
}
}
</script>
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div id="canvas"></div>
</div>
</div>
</div>
</body>
Vehicle.js
function Vehicle(x,y) {
this.pos= createVector(random(width),random(height));
this.target=createVector(x,y);
this.vel= p5.Vector.random2D();
this.acc= createVector();
this.radius=8;
this.maxspeed=10;
this.maxForce=1;
}
Vehicle.prototype.behaviors=function () {
var arrive=this.arrive(this.target);
var mouse= createVector(mouseX,mouseY);
var flee=this.flee(mouse);
arrive.mult(1);
flee.mult(5);
this.applyForce(arrive);
this.applyForce(flee);
}
Vehicle.prototype.applyForce =function (f) {
this.acc.add(f);
}
Vehicle.prototype.update=function () {
this.pos.add(this.vel);
this.vel.add(this.acc);
this.acc.mult(0);
}
Vehicle.prototype.show=function () {
stroke('#0097a7');
strokeWeight(4);
point(this.pos.x,this.pos.y);
}
Vehicle.prototype.arrive= function (target) {
var desired=p5.Vector.sub(target,this.pos);
var d=desired.mag();
var speed=this.maxspeed;
if(d < 100) {
speed=map(d,0,100,0,this.maxspeed)
}
desired.setMag(speed);
var steer=p5.Vector.sub(desired,this.vel);
steer.limit(this.maxForce);
return steer;
}
Vehicle.prototype.flee= function (target) {
var desired=p5.Vector.sub(target,this.pos);
var d= desired.mag();
if(d <50) {
desired.setMag(this.maxspeed);
desired.mult(-1);
var steer=p5.Vector.sub(desired,this.vel);
steer.limit(this.maxForce);
return steer;
} else {
return createVector(0,0);
}
}
Though you could but, you don't have to use p5*js to achieve that animation. Fortunately, I've came across a javascript library called Particle Slider
and as it turns out, yalantis also using the same library for their animation.
Here is how you could accomplish such animation using that library.
let init = () => {
PS.renderText({
text: 'B',
fontFamily: 'Arial',
fontSize: 200,
fontColor: '#00E2FA',
fontWeight: 'bold'
});
var myPS = new ParticleSlider({
ptlGap: 3,
ptlSize: 1,
mouseForce: 70
});
window.onresize = () => {
myPS.width = window.innerWidth;
myPS.height = window.innerHeight;
}
}
window.onload = init;
html, body {
width: 100%;
height: 100%;
overflow: hidden;
background-color: black;
}
<script src="https://istack.000webhostapp.com/PS.js"></script>
<!-- DO NOT CHANGE ANYTHING AFTER THIS LINE -->
<div class="slides">
<div class="slide"> </div>
</div>
<canvas class="draw"></canvas>
<!-- DO NOT CHANGE ANYTHING BEFORE THIS LINE -->
Yes! It's really that easy :)
also, checkout a demo on jsFiddle
for future reference always refer to the official documentation

AngularJS - Display image on top of another image

I am sorry if my codes are messy. I am trying to display image on top of another image in Ionic AngularJS. Basically, when user clicks the "apply" button, it will display the image "toilet.png" on top of the image "PathFindingMap.png".
In my navigation.html, I have the following code snippet:
<button ng-click="apply()" type="button">Apply</button>
<div style="width: 627px; height:975px; background-image: url('img/PathFindingMap.png'); background-repeat: no-repeat; background-size:cover;">
</div>
<div ng-style="navigationStyleToilet[$index]" ng-repeat="o in arr"></div>
In my controller.js, I have the following code snippet:
.controller('NavigationCtrl', function ($scope, NavigationService) {
$scope.myCategory = {}
$scope.apply = function () {
$scope.arr = [];
var strCategoryName = "Washroom";
categoryInfo = NavigationService.fnGetCategoryInfo(strCategoryName);
$scope.navigationStyleToilet = [];
for (i = 0; i < categoryInfo.length; i++)
{
$scope.arr.push(i);
var targetImageX = categoryInfo[i].X;
var targetImageY = categoryInfo[i].Y;
$scope.navigationStyleToilet[i] = {
"z-index":"1",
"position":"absolute",
"width": "100px",
"height": "100px",
"top": targetImageY,
"left":targetImageX,
"background": "url('img/toilet.png')",
"background-repeat": "no-repeat",
}
}
}
})
In my servicesjs I have the following code snippet:
.factory('NavigationService', function () {
var ToiletCoordinates = new Array();
ToiletCoordinates[0] = { X: 16, Y: 100 };
return {
fnGetCategoryInfo: function (strCategoryName) {
if (strCategoryName == "All Booth") {
}
else if (strCategoryName == "Washroom") {
return ToiletCoordinates;
}
}
}
})
Unfortunately, the "toilet.png" image always display below the "PathFindingMap.png", regardless of the X and Y coordinates of the "toilet.png". I have tried many things but I still could not make the "toilet.png" displayed on top of the "PathFindingMap.png". It seems there is something wrong with my code. Can anyone tell me a way to make it work? Thanks!
You can do it with the help of CSS. To add image on the top of another image on button click, you can use ng-class attribute.
var app = angular.module("ap", []);
app.controller("con", function($scope) {
$scope.class = "imgagOnBottom";
$scope.changeClass = function() {
if ($scope.class === "imageOnBottom") $scope.class = "imageOnTop";
else $scope.class = "imageOnBottom";
};
});
.container {
position: relative;
}
.imageOnTop {
position: absolute;
width: 100px;
height: 100px;
border: 1px solid red;
}
.imageOnBottom {
/*whatever css you want.*/
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ap" ng-controller="con">
<div class="container" style="background-image:'PathFindingImage.png';">
<img ng-class="class" / src="toliet.png">
</div>
<button ng-click="changeClass()">Change Class</button>
</body>

How to keep reference to another jQuery object in a jQuery object?

I am writing a simple jQuery plugin for my purpose, which:
creates a background div (for blocking purposes, like a modal dialog). (referenced with backDiv)
shows that background.
shows $(this).
removes background and hides $(this) when background clicked.
I am able to do all of these except 4th one: As I can't save a reference to the background div, I cannot get it back and remove it.
I tried $(this).data('backDiv',backDiv); and $(this)[0].backDiv = backDiv;
I know that there are various plugins that does this including the jQuery's own dialog function, but I want to create my own version.
I cannot keep this variable globally, so, how can I keep a reference to backDiv in a jQuery object, (or DOM object?) if that's even possible at all?
update: I allow multiple of these elements show on top of each other: Nested modal dialogs.
update-2:
(function($) {
$.fn.showModal = function() {
var backDiv = $('<div style="width: 100%; height: 100%; background-color: rgba(55, 55, 55, 0.5); position:absolute;top:0px;left:0px;">This is backDiv</div>');
$(this).data('backDiv', backDiv);
$('body').append(backDiv);
//TODO: bringToFront(backDiv);
$(this).show();
//TODO: bringToFront($(this);
var thisRef = $(this);
backDiv.click(function() {
thisRef.closeModal();
});
return $(this);
};
$.fn.closeModal = function() {
//PROBLEM (null): var backDiv = $(this).data('backDiv');
//backDiv.remove();
$(this).data('backDiv', '');
$(this).hide();
}
}(jQuery));
$(document).ready(function() {
$('#a').showModal();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="a" style="display:none;z-Index:2;background:red; width: 100px; height:50px;position:absolute"></div>
I suggest you to work in terms of complex dom objects, something similar angular directives, basically, you have to work with components that are represented in the dom as Group of Objects.
So, following what I'm saying, your modal component should be something like that:
var Modal = (function($) {
var tpl = '<div style="display:none;" class="modal"><div class="modal-backdrop"></div><div class="modal-content"></div></div>';
function Modal(container) {
var self = this;
this.container = $(container || 'body');
this.tpl = $(tpl).appendTo(this.container);
this.content = $('.modal-content', this.tpl);
this.backdrop = $('.modal-backdrop', this.tpl);
this.isOpened = false;
this.ANIMATION_DURATION = 500;
this.backdrop.click(function(e) { self.toggle(e) });
}
Modal.prototype.show = function(cb) {
var self = this;
cb = $.isFunction(cb) ? cb : $.noop;
this.tpl.fadeIn(this.ANIMATION_DURATION, function() {
self.isOpened = true;
cb();
});
return this;
};
Modal.prototype.hide = function(cb) {
var self = this;
cb = $.isFunction(cb) ? cb : $.noop;
this.tpl.fadeOut(this.ANIMATION_DURATION, function() {
self.isOpened = false;
cb();
});
return this;
};
Modal.prototype.toggle = function() {
if(this.isOpened) {
return this.hide();
}
return this.show();
};
Modal.prototype.setContent = function(content) {
this.content.html($('<div />').append(content).html());
return this;
};
return Modal;
})(window.jQuery);
function ExampleCtrl($) {
var modal = new Modal();
modal.setContent('<h1>Hello World</h1>');
$('#test').click(function() {
modal.show();
});
}
window.jQuery(document).ready(ExampleCtrl);
.modal {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
.modal .modal-backdrop {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background: rgba(0, 0, 0, .8);
}
.modal .modal-content {
width: 300px;
height: 150px;
background: #fff;
border: 1px solid yellow;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -75px;
line-height: 150px;
text-align: center;
}
h1 {
line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Test Modal</button>
Add data-backDiv="" into you dynamic modal div
Change below
var backDiv = $('<div data-backDiv="" style="width: 100%; height: 100%; background-color: rgba(55, 55, 55, 0.5); position:absolute;top:0px;left:0px;">This is backDiv</div>');
In order to retrive data attribute value using JQuery use following code
Syntax
$('selector').data('data-KeyName');
Example
1. $(this).data('backDiv'); // use to retrive value or
2. var temp=$(this).data('backDiv'); // use to retrive value and assign into variable

Categories

Resources