Why can't I get the proper y position in JavaScript? - javascript

When I run the function spin() for the first time, it works. I get the y coordinate of the image called num, which is 470. In every run that follows, it stays 470, even though you can see the image move!
<p id="demo">Click the button to display the y position.</p>
<div style="position:absolute; top:450px; width:300px; height:140px; overflow:hidden; background-color:black;">
<div style="position:relative; top:20px; left:30px; width:80px; height:100px; overflow:hidden; background-color:white;">
<img id="numbers" src="numbers.png" style="position: absolute; left: 8px;">
</div>
<button id="spinButton" style="position: relative; left: 200px; width: 80px;" onclick="spin();">SPIN</button>
</div>
var num = document.getElementById("numbers");
var spn_btn = document.getElementById("spinButton");
function spin() {
//generate a random offset value divisible by 100
var newNumber = (randomNumber() * 100) + 300;
//Debug
document.getElementById("demo").innerHTML = num.y;
TweenMax.to(num, 2, {
y: -newNumber
});
}
function randomNumber() {
var rand = Math.floor(Math.random() * 10);
return rand;
}
(Uses TweetMax)

It looks like the problem is with this line:
TweenMax.to(num, 2, {y:-newNumber});
I'm not familiar with this library so I don't know if it's doing what it's supposed to. Also I don't see the image popping up on my screen anywhere. Can you expand on what the desired functionality is?

Related

Making an image spin with css and jQuery

I'm trying to make a roulette wheel spin when clicking a button, but I can't seem to pass the random number generated from my js file to css
JS
function roulette_spin(btn){
var rand = Math.floor(Math.random() * 720) + 540;
$('.roulette_wheel').css('transform','rotate('+rand+'deg)');
}
HTML
<body>
<div class="roulette_wheel" style="z-index: 0;">
<img src="ayy.jpg" width="500px" height="500px" />
<button value="spin" onclick="roulette_spin(this)">SPIN</button>
</div>
Here is a working example with some updates to your code.
Like #H.Figueiredo suggests, I've changed the rotation selector to the img to avoid the rotation of the button.
HTML
<div class="roulette_wheel" style="z-index: 0;">
<img src="https://picsum.photos/200/300" width="500px" height="500px" />
<button class="spin" value="spin">SPIN</button>
</div>
CSS
function roulette_spin(btn){
var rand = Math.floor(Math.random() * 720) + 540;
$('.roulette_wheel img').css('transform','rotate('+rand+'deg)');
}
$('.spin').click(function(){
roulette_spin($(this).siblings('img'));
});
See this fiddle
I'd say the roulette_wheel class is not assigned to the proper element, the image.
Besides setting the rotate transform won't make the wheel spin, but will just change its rotation angle once (and here without any transition).
Below you will find a working example of assigning a transform style in an animation process.
JQuery calls were replaced by vanilla selectors (getElementsByClassName, getElementById) and style object manipulation instead of JQuery's css method.
Also, look into documentation for requestAnimationFrame
(OK I was a little bored here :) )
var force = 0;
var angle = 0;
var inertia = 0.985;
var minForce = 15;
var randForce = 15;
var rouletteElem = document.getElementsByClassName('roulette_wheel')[0];
var scoreElem = document.getElementById('score');
var values = [
0,27,10,25,29,12,8,19,31,18,6,21,33,16,4,
23,35,14,2,0,28,9,26,30,11,7,20,32,17,5,
22,34,15,3,24,36,16,1
].reverse();
function roulette_spin(btn){
// set initial force randomly
force = Math.floor(Math.random() * randForce) + minForce;
requestAnimationFrame(doAnimation);
}
function doAnimation() {
// new angle is previous angle + force modulo 360 (so that it stays between 0 and 360)
angle = (angle + force) % 360;
// decay force according to inertia parameter
force *= inertia;
rouletteElem.style.transform = 'rotate('+angle+'deg)';
// stop animation if force is too low
if (force < 0.05) {
// score roughly estimated
scoreElem.innerHTML = values[Math.floor(((angle / 360) * values.length) - 0.5)];
return;
}
requestAnimationFrame(doAnimation);
}
<body>
<div style="z-index: 0; position: relative">
<img class="roulette_wheel" src="http://pngimg.com/uploads/roulette/roulette_PNG14.png" width="300px" height="300px" />
<div style="position: absolute; top: 0px; left: 150px; background-color: red; width: 1px; height: 40px;"></div>
<button value="spin" onclick="roulette_spin(this)">SPIN</button>
<span id="score"></span>
</div>
Try this:
<html>
<body>
<div class="roulette_wheel" style="z-index: 0;">
<img src="ayy.jpg" width="500px" height="500px" />
<button value="spin" onclick="roulette_spin()">SPIN</button>
</div>
<script>
function roulette_spin(){
var rand = Math.floor(Math.random() * 720) + 540;
document.querySelector('.roulette_wheel').style.transform = 'rotate('+rand+'deg)';
}
</script>
</body>
</html>

Position 5 divs randomly

I'm completely stuck here. I'm trying to create a program where i have 5 different divs. They need to be placed at random position when running the program. And they need to switch position when i drag my mouse over them. So far i've done this. (which is completely wrong).
function Init()
{
div = document.getElementById("pixel");
div = document.getElementById("pixel1");
div = document.getElementById("pixel2");
div = document.getElementById("pixel3");
div = document.getElementById("pixel4");
spaceW = screen.height - div.height;
spaceH = screen.width - div.width;
setTimeout(moveIt, 0);
}
function moveIt()
{
div.style.top = (100*Math.random()) + "%";
div.style.left = (100*Math.random()) + "%";
}
<body onload="Init()">
<div id="pixel" style="background-color:blue; position:fixed; height:50px; width:50px; font-size:25px;"/>
<div id="pixel1" style="background-color:green; position:fixed; height:50px; width:50px; font-size:25px;"/>
<div id="pixel2" style="background-color:orange; position:fixed; height:50px; width:50px; font-size:25px;"/>
<div id="pixel3" style="background-color:yellow; position:fixed; height:50px; width:50px; font-size:25px;"/>
<div id="pixel4" style="background-color:red; position:fixed; height:50px; width:50px; font-size:25px;"/>
</body>
Can someone nudge me in the right direction because this clearly doesn't work.
check out after fix some syntax error like Pal Singh mention
AND
add all div(s) to one array so can be easy to control it
add [getRandomNum() , percentwidth() , percentHeight()] functions to keep div(s) in page
add moveIt() function to do some animation when move
function RandomIt()
{
var div_array = [];
div_array.push(document.getElementById("pixel"));
div_array.push(document.getElementById("pixel1"));
div_array.push(document.getElementById("pixel2"));
div_array.push(document.getElementById("pixel3"));
div_array.push(document.getElementById("pixel4"));
div_array.forEach(function(entry) {
moveIt(entry,getRandomNum(1,100 - percentwidth(entry)),getRandomNum(1,100 - percentwidth(entry)))
});
}
function getRandomNum(min, max) {
return Math.random() * (max - min) + min;
}
function percentwidth(elem){
return ((elem.offsetWidth/window.innerWidth)*100).toFixed(2);
}
function percentHeight(elem){
return ((elem.offsetHeight/window.innerHeight)*100).toFixed(2)+'%';
}
function moveIt(elem,target_x,target_y) {
var pos_x = 0;
var pos_y = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos_x == target_x && pos_y == target_y) {
clearInterval(id);
} else {
if(pos_x < target_x){
pos_x++;
elem.style.left = pos_x + '%';
}
if(pos_y < target_y){
pos_y ++;
elem.style.top = pos_y + '%';
}
}
}
}
<body onload="RandomIt()">
<button onclick="RandomIt()">RandomIt</button>
<div id="pixel" style="background-color:blue; position:fixed; height:50px; width:50px; font-size:25px;"></div>
<div id="pixel1" style="background-color:green; position:fixed; height:50px; width:50px; font-size:25px;"></div>
<div id="pixel2" style="background-color:orange; position:fixed; height:50px; width:50px; font-size:25px;"></div>
<div id="pixel3" style="background-color:yellow; position:fixed; height:50px; width:50px; font-size:25px;"></div>
<div id="pixel4" style="background-color:red; position:fixed; height:50px; width:50px; font-size:25px;"></div>
</body>
I've added your code to fiddle: https://jsfiddle.net/x05b5suz/2/
Few things I would like to tell you:
div = document.getElementById("pixel");
div = document.getElementById("pixel1"); // This is wrong
div = document.getElementById("pixel2");
You should declare your variable with var keyword and their name should be unique in a scope of a function otherwise you are just overwriting them. So you can name them var div1, var div2 so on.
In HTML, you need to close your <div>...</div> tags, div are not supposed to be quick closed.
I hope this helps

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

Add rotateY(36deg) every 5 Sec in jquery

I have one problem that is was how to add rotateY(36deg) every 5 sec.
like:- 36deg after 5 sec it will become 72deg like so on
this is link:-
but there is no autoplay option.
http://www.jqueryscript.net/demo/Minimal-3D-Perspective-Carousel-with-jQuery-CSS3-3D-Carousel/
this is some css approach with jquery see on link FIDDLE
and this is code snippet
also u can add animation by searching little bit more
var a = 0;
$(document).ready(function(){
setInterval(function() {
a=a+36;
console.log(a);
$('.numcountbyinterval').text(a);
$('.rotate').css({ 'transform': 'rotateY(' + a + 'deg)'});
}, 500);
});
.rotate{
background-color:#ccc;
width:100px;
height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="numcountbyinterval">0</span>
<div class="rotate">
Box inside wow
</div>
I set 500ms for the faster effect. Change 500 into 5000 to get 5sec and also remove perspective and perspective-origin css properties if you prefer 2d effect.
var box = document.getElementById('box');
var time = 5000;
var degPerTime = 36;
var framesPersecond = 32;
var intervalTime = 1000/degPerTime;
var degPerInterval = (degPerTime*intervalTime)/time
var rotate = 0;
setInterval(function(){
rotate -= degPerInterval;
box.style.transform = 'translateZ(-385px) rotateY('+rotate+'deg)';
},intervalTime);
body{
perspective: 500px;
perspective-origin: 10% 10%;
}
#box{
width:200px;
height:200px;
background-color:#33aaff;
position:relative;
top:100px;
left:100px;
}
<div id="box"></div>

Custom JQuery Slider (auto-slide)

I'm trying to make image slider with my own without using plugins.
1st question : How to make the animation horizontally
2nd question : Whatever the size of the image, it must cover the height and width of its container, but keeping the proportionalities original image. The image can be rendered partially. How to make this?
3rd question : About the code of the slide, if anyone finds any improvement to make it lighter and more elegant, would be welcome.
$(function(){
setInterval(function(){
var displayed = $(".img-header.displayed");
displayed.animate({opacity : 0}, 500, function() {
displayed.css("display","none");
displayed.addClass("not-displayed").removeClass("displayed");
if(displayed.next(".img-header.not-displayed").length == 0){
$(".img-header:first").css("display","inline-block").css("opacity","1");
$(".img-header:first").addClass("displayed").removeClass("not-displayed");
$(".img-header:first").animate({opacity : 1}, 500);
}
else{
displayed.next(".img-header.not-displayed").css("display","inline-block").css("opacity","1");
displayed.next(".img-header.not-displayed").addClass("displayed").removeClass("not-displayed");
displayed.next(".img-header.not-displayed").animate({opacity : 1}, 500);
}
});
}, 4000);
});
#slider-container{height: 200px; width: 200px;}
#slider-container img.img-header{ width: 100%; height: auto;}
.displayed{display: inline-block;}
.not-displayed{display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider-container">
<img class="img-header displayed" src="http://i.stack.imgur.com/AIHnl.png" />
<img class="img-header not-displayed" src="http://i.stack.imgur.com/XQrms.png" />
</div>
I think you might be looking for something like this.
The slider here is position:relative; with top:100px; you can set as per your requirement. Still i suggest you to keep it positioned relative.
Slider has width:700px and height:500px;, you can change as per your requirement, it will be fine for whatever aspect ratio of image you have or all images with different aspect ratio.
There is an array for images to load which are serially numbered in one location, so you may give little more understanding into that. I have made a comment for that in JS file
Also you could change slider speed and delay as per your requirements.
When you hover over image it will pause the slider, which resumes after you leave image.
Snippet :
$(document).ready(function(){
var noPannel = document.getElementsByClassName("pannel").length;
var i;
var imgArr = [ ];
var pannelWidth = $(".slider_holder").width();
var totalWidth = noPannel*pannelWidth;
for (i=1;i<=noPannel;i++)
{
imgArr[i] = "http://www.picget.net/background/" + i + ".jpg"; //if you have somewhere on other path
//imgArr[i] = " " + i + ".jpg"; //use this if you have image in same folder/path.
}
for(i=1;i<=noPannel;i++)
{
$(".pannel:nth-child("+i+")").css("background","url("+imgArr[i]+")");
}
function jsslider()
{
var curScroll = $(".slider").scrollLeft();
var endScroll = totalWidth - (pannelWidth*2);
if(curScroll<=endScroll)
{
$(".slider").animate({scrollLeft: '+=' + pannelWidth +'px'},900,"swing");// Replace 900 for speed
}
else
{
$(".slider").animate({scrollLeft: '0px'},500,"swing"); // Replace 500 for speed to go bck to first
}
}
var interval = setInterval(jsslider, 3000); // Replace 3000 for delay between each slide.
$(".pannel").hover(function () {
clearInterval(interval);
}, function () {
interval = setInterval(jsslider, 3000); // Replace 3000 for delay between each slide.
});
}); // document.ready ENDS
html, body, *
{
margin:0px;
width:100%;
height:100%;
}
.slider_holder
{
margin-left:auto;
margin-right:auto;
display:block;
position:relative;
top:100px;
width:1024px;
height:768px;
background:#eee;
overflow:hidden;
}
.slider
{
width:auto;
height:100%;
width:100%;
white-space: nowrap;
overflow:hidden;
}
.pannel
{
margin:0px;
display:inline-block;
width:100%;
height:calc(100% - 1px);
/*border:1px solid red;*/
background-size:cover !important;
background-repeat:no-repeat;
background-position:50% 50% !important;
position:relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="sliderFunc()">
<div class="slider_holder">
<div class="slider">
<span class="pannel"> </span>
<span class="pannel"> </span>
<span class="pannel"> </span>
<span class="pannel"> </span>
<span class="pannel"> </span>
</div>
</div>
</body>

Categories