How should I code this jQuery code in Javascript? - javascript

This exercise I need a function that moves the div randomly inside of the body when I click with the left button mouse.
I'm having some difficulties to swap this code(jquery) into javascript. How would it be?
var counter = 0;
var div = document.getElementsByClassName('a');
function click() {
if (counter < 1) {
var pos = makeNewPosition();
this.style.left = pos[1] + 'px';
this.style.top = pos[0] + 'px';
}
}
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = window.innerHeight = -50;
var w = window.innerWidth = -50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
<div onclick="click()" class="a">Click</div>
This is the jQuery that I wanted to code in javascript.
$(document).ready(function(){
var counter = 0;
$('.a').click( function () {
if (counter < 1 ) {
var pos = makeNewPosition();
this.style.left = pos[1] +'px';
this.style.top = pos[0] +'px';
}
});
});
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}

JavaScript:
window.addEventListener("load", function() {
var counter = 0,
div = document.querySelector(".a");
div.addEventListener("click", function() {
if (counter < 1) {
var pos = makeNewPosition();
this.style.left = pos[1] + 'px';
this.style.ltop = pos[0] + 'px';
}
counter++;
});
});
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = window.innerHeight -50;
var w = window.innerWidth -50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
.a {
position: absolute;
top: 100;
left: 100
}
<div class="a">Click</div>
Based on this jQuery:
$(function() {
var counter = 0;
$('.a').click(function() {
if (counter < 1) {
var pos = makeNewPosition();
$(this).css({
"left": pos[1] + 'px',
"top": pos[0] + 'px'
});
}
counter++;
});
});
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
.a {
position: absolute;
top: 100;
left: 100
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a">Click</div>

The most idiomatic way would be to first get a reference to the element
const div = document.getElementsByClassName('a')[0];
then add an event listener to the element
div.addEventListener('click', click); //Attach your handler function to the event

Related

Alternative to element.getBoundingClientRect()

I have been using getBoundingClientRect(). At the beginning, I'm getting performance issues due to this. If I remove this method from my code, there is working well. Any alternatives to getBoundingClientRect() in javascript.
In this sample, I have created 2000 elements in button click and changed their positions in another button click. In that, I'm getting performance issues when using getBoundingClientRect().
Anyone help me to resolve this.
document.getElementById("click1").onclick = function() {
for (var i = 0; i < 2000; i++) {
var ele = document.createElement("DIV");
ele.id = i + '';
ele.className = "square";
ele.setAttribute("style", "position: absolute;left: 200px; top: 100px");
document.getElementById("marker").appendChild(ele);
}
};
document.getElementById("click").onclick = function() {
var markerCollection = document.getElementById("marker");
var width = 20,
height = 20;
var radius = width * 2;
var area = 2 * 3.14 * radius;
var totalMarker = 0;
var numberOfMarker = Math.round(area / width);
totalMarker += numberOfMarker;
var percent = Math.round((height / area) * 100);
percent =
markerCollection.children.length - 1 < numberOfMarker ?
100 / markerCollection.children.length - 1 :
percent;
var angle = (percent / 100) * 360;
var centerX = 200,
centerY = 100;
var count = 1;
var newAngle = 0,
first = false;
var dt1 = 0,
dt2 = 0;
dt1 = new Date().getTime();
for (var i = 0; i < markerCollection.children.length; i++) {
if (i != 1 && (i - 1) % totalMarker === 0) {
count++;
radius = (width + 10) * count;
newAngle = 0;
area = 2 * 3.14 * radius;
numberOfMarker = Math.round(area / width);
percent = Math.round((height / area) * 100);
angle = (percent / 100) * 360;
totalMarker += numberOfMarker;
}
var x1 = centerX + radius * Math.sin((Math.PI * 2 * newAngle) / 360);
var y1 = centerY + radius * Math.cos((Math.PI * 2 * newAngle) / 360);
var offset = markerCollection.children[i].getBoundingClientRect();
markerCollection.children[i]["style"].left = (x1 - (offset.width / 2)) + "px";
markerCollection.children[i]["style"].top = (y1 - (offset.height / 2)) + "px";
newAngle += angle;
}
dt2 = new Date().getTime();
alert(dt2 - dt1);
};
<!DOCTYPE html>
<html>
<head>
<style>
.square {
height: 20px;
width: 20px;
background-color: #555;
border: 1px solid red;
}
</style>
</head>
<body>
<button id="click1">Create Element</button>
<button id="click">Click To Change</button>
<div id='marker' style="width: 350px;height: 200px;border: 1px solid red">
</div>
</div>
<script>
</script>
</body>
</html>
If I'm not misreading your code, all you're using getBoundingClientRect() for is to calculate the width and height of an element you already know the width and height of (20x20px).
Just use your width and height variables directly, or possibly avoid having to do the offset calculation entirely, add transform: translate(-50% -50%) to the element's style.

Move multiple images on a page in different directions

I have multiple images on a page that are loaded dynamically using PHP. I want them to all move in different directions across the screen.
So far what I have, the images move in a random direction but all in the same position.
PHP:
<?php foreach($logos as $logo) {
$logoName = $logo['Logo_Link']; ?>
<img class="imglogo" src="images/<?php echo $logoName ?>" />
<?php } ?>
JS:
$(document).ready(function() {
animateDiv();
});
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
$container = ($container || $(window));
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var $target = $('.imglogo');
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.imglogo').animate({
top: newq[0],
left: newq[1]
}, speed, function() {
animateDiv();
});
}
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
I just made a loop in the animateDiv function
animateDiv();
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
$container = ($container || $(window));
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var $target = $('.imglogo');
for(let i=0; i<$target.length; i++){
var newq = makeNewPosition($($target[0]).parent());
var oldq = $($target[0]).offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$($('.imglogo')[i]).animate({
top: newq[0],
left: newq[1]
}, speed, function() {
animateDiv();
});
}
}
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
.imglogo{
width: 40px;
height: 40px;
background-color: blue;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imglogo"></div>
<div class="imglogo"></div>
<div class="imglogo"></div>
<div class="imglogo"></div>
<div class="imglogo"></div>
<div class="imglogo"></div>
<div class="imglogo"></div>

JQuery Animate setTimeout

As the subject, how can I set timeout for below jQuery?? Thank you
$(document).ready(function(){
animateM();
});
function newPosition(){
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateM(){
var newq = newPosition();
$('.animateM').animate({ top: newq[0], left: newq[1] }, function(){
animateM();
});
};
In a basic scenario, the preferred, cross-browser way to pass parameters to a callback executed by setTimeout is by using an anonymous function as the first argument.:
function newPosition(){
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
$(document).ready(function(){
var newq = newPosition();
setTimeout(function() {
$('.animateM').animate({
top: newq[0],
left: newq[1],
});
, 2000 ); // 2000 is duration
});
Try This
$(document).ready(function(){
var newq = newPosition();
$(".animateM").animate({left:newq[1]}, "2000")
.animate({top:newq[0]}, "5000");
});
function newPosition(){
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="animateM" style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

remove elements in dom animation

I try to delete some animated elements if they pass the screen height. For that an array will be checked in a for loop. The array have the id's of the created div's. Theoretically should all div's which have an y position which is higher than the screen height become removed and the values from the array deleted. But now it becomes every n element removed. Know anyone the issue for that? box = setInterval(newbox, 1000); affect the behaviour when I change the interval time.
fiddle
var cx = wwidth / 100;
var cy = wheight / 100;
var maxpos = cx * 80;
var speed;
var box;
var counter = 0;
var rectids = [];
var deleting;
function newbox() {
var allpositions = Array(0, cx * 25, cx * 50, cx * 75);
var rectpos = allpositions[Math.floor(Math.random() * allpositions.length)];
speed = 0;
var box = document.createElement('div');
counter++;
box.className = "game-btn";
box.id = 'n' + counter;
box.style.cssText = "top:" + speed + "px;left:" + rectpos + "px;width:" + cx * 25 + "px;height:" + cy * 10 + "px;position:absolute";
console.log(rectpos);
document.body.appendChild(box);
rectids.push(box.id);
}
function game() {
box = setInterval(newbox, 1000);
animaterects = setInterval(function () {
speed += cx / 300;
$(".game-btn").css("top", "+=" + speed + "px");
}, 10);
deleting = setInterval(function () {
for (var i = 0; i < rectids.length; i++) {
var x = $("#" + rectids[i]).position();
if (x.top > wheight) {
$("#" + rectids[i]).remove();
rectids.splice(rectids[i]);
}
}
}, 50);
}
game();

stopping rotating images when popup dialog box is active

I am using javascript functions to rotate images in an orbital manner. I also have created a popup dialog box as well. What I am trying to do is have it so that when the dialog box is active, the images stop even if i were to mouseout from the image.
Here is my javascript functions I have made:
var popupStatus = 0;
var timer = null;
var m = {
Z : 100,
xm : 0,
xmm : .25,
ymm : 0,
ym : 0,
mx : 0,
nx : 0,
ny : 0,
nw : 0,
nh : 0,
xR : 0,
nI : 0,
scr : 0,
img : 0,
run : function () {
m.xm += (m.xmm - m.xm) * .1;
if (m.ym < m.nw * .15) m.ym++;
m.xR += m.xm;
for (var i = 0; i < m.nI; i++){
var A = (i * 360 / m.nI) + m.xR;
var x = Math.cos(A * (Math.PI / 180));
var y = Math.sin(A * (Math.PI / 180));
var a = m.img[i];
a.style.width = ''.concat(Math.round(Math.abs(y * m.ym) + y * m.Z), 'px');
a.style.left = ''.concat(Math.round((m.nw * .5) + x * ((m.nw * .5) - (m.nw * .05)) - ((Math.abs(y * m.ym) + y * m.Z) * .5)), 'px');
a.style.height = ''.concat(Math.round(m.ym + y * m.Z), 'px');
a.style.top = ''.concat(Math.round((m.nh * .5) - (m.ym * .5) - x * (m.Z * .5) - (m.ymm * y)), 'px');
a.style.zIndex = 600 + Math.round(y);
m.setOpacity(a, (y * 50) + 100);
}
timer = setTimeout(m.run, 30);
},
resize : function () {
m.nx = m.scr.offsetLeft;
m.ny = m.scr.offsetTop;
m.nw = m.scr.offsetWidth;
m.nh = m.scr.offsetHeight;
},
mousemove : function (e) {
if (window.event) e = window.event;
m.xmm = (m.nx + (m.nw * .5) - (e.x || e.clientX)) / (m.nw * .25);
m.ymm = (m.ny + (m.nh * .5) - (e.y || e.clientY)) / (m.nh * .005);
},
setOpacity : function (obj, a) {
if (a < 0) a = 0; else if (a > 100) a = 100;
if (obj.filters) obj.filters.alpha.opacity = a;
else obj.style.opacity = a / 100;
},
init : function () {
m.scr = document.getElementById("screen");
m.img = m.scr.getElementsByTagName("img");
m.nI = m.img.length;
window.onresize = m.resize;
m.resize();
m.ym = m.Z;
m.run();
}
}
function stop(){
clearTimeout(timer);
}
onload = function() {
m.init();
}
function loadPopup(){
//loads popup only if it is disabled
if(popupStatus==0){
$("#backgroundPopup").css({
"opacity": "0.7"
});
$("#backgroundPopup").fadeIn("slow");
$("#popupContact").fadeIn("slow");
popupStatus = 1;
}
();
}
function disablePopup(){
//disables popup only if it is enabled
if(popupStatus==1){
$("#backgroundPopup").fadeOut("slow");
$("#popupContact").fadeOut("slow");
popupStatus = 0;
}
}
//centering popup
function posPopup(){
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $("#popupContact").height();
var popupWidth = $("#popupContact").width();
//centering
$("#popupContact").css({
"position": "absolute",
"top": windowHeight/2-popupHeight/350,
"left": windowWidth/2-popupWidth/8
});
//only need force for IE6
$("#backgroundPopup").css({
"height": windowHeight
});
}
//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){
//LOADING POPUP
//Click the button event!
$("#button").click(function(){
//centering with css
posPopup();
//load popup
loadPopup();
stop();
});
});

Categories