Rotate shapes when clicking on on circle in JavaScript - javascript

When clicking on a circle, another shape should rotate, but there is something wrong with my loop. Here's my code:
var Degree = 0;
function RotateDiv(obj) {
let arak = document.getElementsByTagName('div');
for (let i in arak) {
Degree += 10
arak[i].style.rotate = 'rotate(' + deg + 'deg)';
}
}
<div onclick="RotateDiv(this)" class="button">rotate</div>
<div class="s1"></div>
<div class="s2"></div>
<div class="s3"></div>
<div class="s4"></div>
It only works the first time. I get this message in the debugger:
Paused on exception
ReferenceError: deg is not defined

ReferenceError: deg is not defined
Because of you don't have deg replaced with Degree
to rotate a div we have to use transform = 'rotate(' + Degree + 'deg)'
if you want all div to rotate same deg you have to move the Degree += 10 to top of forEach
var Degree = 0;
function RotateDiv(obj) {
let arak = document.querySelectorAll(".example")
arak.forEach((i) => {
Degree += 10
i.style.transform = 'rotate(' + Degree + 'deg)';
})
}
.example {
height: 20px;
margin: 10px;
background-color: red
}
<div onclick="RotateDiv(this)" class="button">rotate</div>
<div class="example s1"></div>
<div class="example s2"></div>
<div class="example s3"></div>
<div class="example s4"></div>

Related

Rotate images as scrolls and in viewport according to scroll percentage using jquery

I'm trying to rotate two images on scroll, I want to rate the image from the 0 - 13deg range according to the percentage of mouse scroll when it comes in view.
There are 4-5 sections each section has these two images.
I just coded the first section of image rotation which I want to achieve for others too, but my .each function is not working.
I just have knowledge of HTML and CSS and a little bit of jquery. So I don't know what's wrong I'm doing.
[
$(window).scroll(function() {
$( ".image" ).each(function() {
var $this= $(this);
var h = window.innerHeight;
var scrollTop = $(window).scrollTop();
var elementOffset = $this.offset().top;
var distance = (elementOffset - scrollTop );
var scrollPercent = 100 - distance / $(window).height() * 100 ;
var speed = scrollPercent*.175;
if(elementOffset < h){
$this.find(".left-image").css({ 'transform': 'rotate(-' + speed + 'deg)'});
$this.find(".left-image").css({ 'transform': 'rotate(-' + speed + 'deg)'});
$this.find(".right-image").css({ 'transform': 'rotate(' + speed + 'deg)'});
}
if(scrollPercent >= 76){
$this.find(".left-image").css({ 'transform': 'rotate(' + "-13" + 'deg)'});
$this.find(".right-image").css({ 'transform': 'rotate(' + "13" + 'deg)'});
}
if(scrollPercent <= 15){
$this.find(".left-image").css({ 'transform': 'rotate(' + "0" + 'deg)'});
$this.find(".right-image").css({ 'transform': 'rotate(' + "0" + 'deg)'});
}
});
});
section{
display:flex;
}
.content{
background:#fff;
padding:20px;
min-height:200px;
width:50%
}
.left-image {
position: relative;
z-index: 2;
top: -15px;
right: -45px;
width:50%
}
.right-image {
position: relative;
z-index: 1;
}
.image, .image img{
width:50%;
}
.image{
display:flex;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section style="background:red;padding:60px; min-height:300px">
</section>
<section style="background:blue;padding:60px; min-height:300px">
<div class="content">
content here
</div>
<div class="image">
<img src="https://drive.google.com/uc?export=view&id=1EEvY9MW3Ea85TjpTW_RnzRGCx7JXOq6U" class="left-image" />
<img src="https://drive.google.com/uc?export=view&id=1iRneWpuEsCsNPK3xo7cBgojSC4N3Hxea" class="right-image" />
</div>
</div>
</section>
<section style="background:green;padding:60px; min-height:300px">
<div class="content">
content here
</div>
<div class="image">
<img src="https://drive.google.com/uc?export=view&id=1EEvY9MW3Ea85TjpTW_RnzRGCx7JXOq6U" class="left-image" />
<img src="https://drive.google.com/uc?export=view&id=1iRneWpuEsCsNPK3xo7cBgojSC4N3Hxea" class="right-image" />
</div>
</div>
</section>
<section style="background:yellow;padding:60px; min-height:300px">
<div class="content">
content here
</div>
<div class="image">
<img src="https://drive.google.com/uc?export=view&id=1EEvY9MW3Ea85TjpTW_RnzRGCx7JXOq6U" class="left-image" />
<img src="https://drive.google.com/uc?export=view&id=1iRneWpuEsCsNPK3xo7cBgojSC4N3Hxea" class="right-image" />
</div>
</div>
</section>
Codepen:https://codepen.io/Kroshan/pen/RwyVaVm

How to draw a line connector between two icons displayed in two different div.

I have displayed one Icons in one Div element. I need to draw a connecting line between those Icons. Please note that the Div is a dynamic element.
I have displayed the current Image below.
Expected image is displayed below.
Please guide me how to do that. Thanks in advance.
Here is a small demo that will help you know how to use jsPlumb achieve what you want.
jsPlumb.ready(function() {
jsPlumb.connect({
source:"firstItem",
target:"secondItem",
endpoint:"Dot"
});
});
span{
display:inline-block;
height:50px;
width:100px;
background-color:yellow;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jsPlumb/1.4.1/jquery.jsPlumb-1.4.1-all-min.js"></script>
<div id="diagramContainer">
<div >
<span id="firstItem">Smiley1</span>
</div>
<div >
<span style="float:right" id="secondItem">Smiley2</span>
</div>
</div>
Hope it helps :)
The concept is to draw a div with absolute position inside of "starting point" and rotate it on an angle between 2 points:
// a,b = jquery results i.e. a=$('#smile1'), b=$('#smile2'),
function dist(a,b) {
let o1 = a.offset(), o2 = b.offset();
return Math.sqrt(Math.pow(o1.top - o2.top,2) + Math.pow(o1.left - o2.left,2));
}
function angle(a, b) {
let ao = a.offset(), bo = b.offset();
dx = ao.left-bo.left, dy = ao.top-bo.top;
return Math.PI + Math.atan2(dy, dx);
}
function drawConnection(a,b) {
$('.line').remove();
let d = dist(a,b);
a.removeClass('first');
let ang = d<10
? 0
: (angle(a,b) * 180)/ Math.PI;
a.append(
$('<div>').addClass('line')
.css({
width: Math.round(d) +'px',
transform: 'rotate(' + Math.round(ang) + 'deg)'
})
);
return ang;
}
CSS for the line should be:
.line {
position: absolute;
transform-origin: top left; // to make it rotate around top-left
border-top: solid 2px blue; // set any color
top: 10px; // center of your "smile"
left: 10px;
}
Here is the working example

Animation back to it's starting point

I've made a small program to animate an image back and forth. Now the first jobbra button works well the image is animating picel by pixel to the right, but my back button balra doesn't work, the image doesn't move back to it's starting point. Is anyone has any idea why, please help. Thank you
var jobbAnim = 1;
var speed = 1;
var balAnim = 400;
function jobbra() {
if (jobbAnim < 400) {
jobbAnim = jobbAnim + speed;
}
document.getElementById("ilonakep").style.marginLeft = jobbAnim + "px";
window.requestAnimationFrame(jobbra);
}
function balra() {
if (balAnim >= 400) {
balAnim = balAnim - speed;
}
document.getElementById("ilonakep").style.marginRight = balAnim + "px";
window.requestAnimationFrame(balra);
}
<div id="container">
<div id="ilonakep">
<img src="/img/ilona.jpg" alt="ilona">
</div>
</div>
<p id="gombok">
<button onclick="balra()">Balra</button>
<button onclick="jobbra()">Jobbra</button>
</p>
You should use cancelAnimationFrame to make sure you only have one animation playing at a time, otherwise a new animation will be started every time you click one of the buttons. I also, suggest you animate the element's position (or better yet, use transform: translate();) rather than the margin. It isn't as ideal as using CSS transitions, but it makes it more intuitive.
var left = 0;
var speed = 1;
var anim;
function jobbra() {
if (anim) {
window.cancelAnimationFrame(anim);
}
if (left < 400) {
left = left + speed;
}
document.getElementById("ilonakep").style.left = left + "px";
anim = window.requestAnimationFrame(jobbra);
}
function balra() {
if (anim) {
window.cancelAnimationFrame(anim);
}
if (left > 0) {
left = left - speed;
}
document.getElementById("ilonakep").style.left = left + "px";
anim = window.requestAnimationFrame(balra);
}
<div id="container">
<div id="ilonakep" style="position: relative; display: inline;">
<img src="/img/ilona.jpg" alt="ilona">
</div>
</div>
<p id="gombok">
<button onclick="balra()">Balra</button>
<button onclick="jobbra()">Jobbra</button>
</p>
Try this:
var jobbAnim = 1;
var speed = 1;
var balAnim = 400;
function jobbra() {
if (jobbAnim < 400) {
jobbAnim = jobbAnim + speed;
}
document.getElementById("ilonakep").style.marginLeft = jobbAnim + "px";
window.requestAnimationFrame(jobbra);
}
function balra() {
if (balAnim > 399) {
balAnim = balAnim - speed;
}
document.getElementById("ilonakep").style.marginLeft = balAnim + "px"; //This will reset the element to the left
document.getElementById("ilonakep").style.marginRight -= balAnim + "px"; //This will move it to the left
window.requestAnimationFrame(balra);
}
<div id="container">
<div id="ilonakep">
<img src="/img/ilona.jpg" alt="ilona">
</div>
</div>
<p id="gombok">
<button onclick="balra()">Balra</button>
<button onclick="jobbra()">Jobbra</button>
</p>
Using pure CSS animations, you can easily modify how it looks as well. Check out more here - https://www.w3schools.com/css/css3_animations.asp
function addLeft() {
document.getElementById("container").classList.add("slideLeft");
}
function addRight() {
document.getElementById("container").classList.add("slideRight");
}
.slideRight {
animation-name: slideRight;
animation-duration: 4s;
animation-fill-mode: forwards;
}
#keyframes slideRight {
from {
margin-left: 0;
}
to {
margin-left: 50%;
}
}
.slideLeft {
animation-name: slideLeft;
animation-duration: 4s;
animation-fill-mode: forwards;
}
#keyframes slideLeft {
from {
margin-left: 50%;
}
to {
margin-left: 0;
}
}
<div id="container">
<div id="ilonakep">
<img src="/img/ilona.jpg" alt="ilona">
</div>
</div>
<p id="gombok">
<button onclick="document.getElementById('container').classList.add('slideLeft')">Balra</button>
<button onclick="document.getElementById('container').classList.add('slideRight')">Jobbra</button>
</p>

Interactjs rotation shifts the position

I am trying to rotate, resize and drag an image using interactjs.
I am using pinch to zoom for resizing.
After rotating the image the drag feature does't work well and positions the image at wrong coordinates.
I also tried to move the img by (width/2,height/2) before rotating so that it retains its position, but this stopped resize and rotate feature.
Here is the code I am using.
The pinch to zoom and rotate only works on touch phone :
Here is the fiddle(Please check in Phone for pinch-to-zoom and rotate).
HTML
<div style="display:flex;flex-direction:row;border:solid grey 2px;border-radius:20px;position:relative;float:left;background-color:silver;width:100%">
<img class="Choice" src="http://gifmemorecreativity.com/images/design/small/2014-12-02/19220-50b6c96d8aa44ed1511a962bae279f25.png" style="width:150px; height:150px;" />
<img class="Choice" src="http://gifmemorecreativity.com/images/design/small/2014-04-27/5895-37981e6fff910eef9907adaf99faa6b6.png" style="width:150px; height:150px;" />
<img class="Choice" src="http://gifmemorecreativity.com/images/design/small/2014-04-27/5728-08fc043472bfa4cc9ba6d7c4a90324e0.png" style="width:150px; height:150px;" />
<img class="Choice" src="http://gifmemorecreativity.com/images/design/small/2014-11-30/17784-d2820ac7614e8f4eeb755c38bdccadc0.png" style="width:150px; height:150px;" />
<img class="Choice" src="http://gifmemorecreativity.com/images/design/small/2014-04-27/5728-08fc043472bfa4cc9ba6d7c4a90324e0.png" style="width:150px; height:150px;" />
<img class="Choice" src="http://gifmemorecreativity.com/images/design/small/2014-04-27/5895-37981e6fff910eef9907adaf99faa6b6.png" style="width:150px; height:150px;" />
</div>
<div style="display:flex;flex-direction:row;justify-content:space-between;align-items:center;border:solid grey 2px;border-radius:20px;position:relative;float:left;background-color:silver;height:50px;width:150px">
<button id="save" style="width:50px" />
<button id="savetwo" style="height:40px;border-radius:20px;width:70px">Save Image</button>
</div>
<br />
</div>
</div>
SCRIPT
$(document).ready(function(){
$(".Choice").click(function () {
console.log($(this));
var url = '"' + $(this)[0].src + '"';
var index = url.indexOf("http://");
console.log(url);
var modurl = url.substring(index, url.length - 1);
console.log(url);
$(".ChoiceImage").attr("src", modurl);//url appends src to the current uri so I had to split it(suggest alternative )
});
var scale = 1,angle=0;
var gestureArea = document.getElementById('gesture-area');
var scaleElement = document.getElementById('chosenOne');
var scaleElementParent = scaleElement.parentElement;
interact(gestureArea).gesturable({
onstart: function(event) {
},
onmove: function(event) {
angle += event.da;
scale = scale * (1 + event.ds);
scaleElement.style.webkitTransform =
scaleElement.style.transform =
'scale(' + scale + ') rotate('+ angle + 'deg)';
scaleElementParent.style.webkitTransform =
scaleElementParent.style.transform =
'scale(' + scale + ') rotate('+ angle + 'deg)';
dragMoveListener(event);
},
onend: function(event) {
}
}).draggable({ onmove: dragMoveListener });
function dragMoveListener(event) {
var target = event.target.children[0];
console.log(target);
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the posiion attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
// this is used later in the resizing and gesture demos
window.dragMoveListener = dragMoveListener;
});
The user clicks on an image from the list of images to perform the actions.
Thanks in advance
Your main issue was to scale and rotate the image AND the "gesture area.
So if the gesture detection element is rotated, interac.js only can misinterpret the movements.
I cleaned the code a little... And removed all the unused elements from this answer, like the buttons...
Here is the code in full and a CodePen to try it on a mobile device.
console.clear();
$(".Choice").click(function() {
$(".ChoiceImage").attr("src", $(this).attr("src"));
});
var scale = 1,
angle=0,
gestureArea = $('#gestureArea')[0],
scaleElement = $('.ChoiceImage'),
scaleElementParent = $('#gestureArea');
// Scale and rotate
interact(gestureArea).gesturable({
onstart: function(event) {
},
onmove: function(event) {
angle += event.da;
scale = scale * (1+event.ds);
scaleElement.css({'transform':'scale(' + scale + ') rotate('+ angle + 'deg)'});
//scaleElementParent.css({'transform':'scale(' + scale + ') rotate('+ angle + 'deg)'});
dragMoveListener(event);
},
onend: function(event) {
}
}).draggable({ onmove: dragMoveListener });
// Drag
function dragMoveListener(event) {
var target = $(event.target);
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.attr('data-x')) || 0) + event.dx;
y = (parseFloat(target.attr('data-y')) || 0) + event.dy;
// translate the element
target.css({'transform':'translate(' + x + 'px, ' + y + 'px)'});
// update the posiion attributes
target.attr('data-x', x);
target.attr('data-y', y);
}
// this is used later in the resizing and gesture demos
window.dragMoveListener = dragMoveListener;
#gestureArea{
position:relative;
z-index:999;
width:150px;
height:150px;
background-color:transparent;
border:none;
padding: 0px 0px 0px 0px;
}
.container{
display:flex;
flex-direction:row;
border:solid grey 2px;
border-radius:20px;
position:relative;
float:left;
background-color:silver;
width:100%;
position:fixed;
bottom:0;
}
img{
width:150px;
height:150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/interact.js/1.2.8/interact.min.js"></script>
<div id="gestureArea">
<img id="chosenOne" class="ChoiceImage resize-drag">
</div>
<div class="container">
<img class="Choice" src="http://gifmemorecreativity.com/images/design/small/2014-12-02/19220-50b6c96d8aa44ed1511a962bae279f25.png">
</div>

jquery : Text on moving div (infinite wall)

I need to make an infinite wall which will pull text from database and show it on the wall. I have written this code -
$(function() {
var x = 0;
var y = 100.0;
var z=0;
setInterval(function() {
x -= 0.1;
y -= 0.1;
z++;
if (x <= -100.0){
$("#h1d1").html("loop div 1 :" + z);
x = 0;
}
if (y <= 0){
$("#h1d2").html("loop div 2 :" + z);
y = 100.0;
}
$('#movimg1').css('left', x + "%");
$('#movimg2').css('left', y + "%");
}, 10);
$("#stopbutton").click(function() {
$('#movimg1').stop();
});
})
But the text are not behaving as I wanted it to behave. It changes in the middle of the screen which I don't want. I need the text to change when it is out of view.
https://jsfiddle.net/oa0wdxcx/2/
A couple more things- I want to add a play/pause button. Any advice on how I could achieve that would be much appreciated. Also I want the divs to be inside #wrap div, but if I change the position attribute to relative, the divs don't remain together.
Thanks in advance.
The problem was in the conditions.
if (x <= -100.0) {
z++;
$("#h1d1").html("loop div 1 :" + z);
x = 100; /* change this line */
}
if (y <= -100.0) { /* change this line */
w++;
$("#h1d2").html("loop div 2 :" + w);
y = 100;
}
the conditions says that if any of these two divs reaches left:-100% then the element must place at the end of queue at left:100%.
And one other thing you can combine these if statements and only use x to do the transition.
For start and stop button to work, you should kill the simulation to stop by using clearInterval() function, and call doSimulate() to start again:
var started = true;
$("#stopbutton").click(function () {
if(started) {
clearInterval(sim);
$(this).html('Start');
started = false;
}else{
doSimulate();
$(this).html('Stop');
started = true;
}
});
Here is jsFiddle With Start/Stop Working.
Look at this JSFiddle, i added one more to get a smooth transition back to start.. The third should contain same message as first.
HTML
<body>
<div class="row">
<div class="col-xs-1"></div>
<div id="wrap" class="col-xs-10">
<div class="movimg message1" id="movimg1">
<h1 class="header">start div 1</h1>
</div>
<div class="movimg message2" id="movimg2">
<h1 class="header">start div 2</h2>
</div>
<div class="movimg message1" id="movimg3">
<h1 class="header">start div 1</h1>
</div>
</div>
<div class="col-xs-1"></div>
</div>
<div class="row">
<button class="button" id="startbutton" style="display:none;">Start</button>
<button class="button" id="stopbutton">Stop</button>
</div>
</body>
JavaScript
$(function () {
var x = 200.0;
var interval;
function start(){
interval = setInterval(function () {
x -= 0.1;
if (x <= 0.0) {
x = 200;
}
$('#movimg1').css('left', (x-200) + "%");
$('#movimg2').css('left', (x-100) + "%");
$('#movimg3').css('left', x + "%");
}, 10);
}
start();
$("#stopbutton").click(function () {
window.clearInterval(interval);
$(this).hide();
$("#startbutton").show();
});
$("#startbutton").click(function () {
start();
$(this).hide();
$("#stopbutton").show();
});
})
CSS
body {
overflow: hidden;
}
#wrap {
width: 80%;
left: 10%;
}
.movimg{
position: absolute;
height: 600px;
width: 100%;
background-image: url('https://s-media-cache-ak0.pinimg.com/736x/89/ed/e5/89ede56bcc8243787e55676ab28f287f.jpg');
}
#movimg1 {
left: 0%;
}
#movimg2 {
left: 100%;
}
#movimg3 {
left: 200%;
}
.header {
text-align: center;
}
.button{
top: 600px;
position: relative;
}
UPDATE
Now with Stop and Start buttons: JSFiddle

Categories