OnClick function to rotate a div element - javascript

I am new to Javascript. I am writing a code where I am trying to rotate a square with every click. I was able to do it by clicking the square div element itself. But I wanna rotate the element using the button only. I am stuck with this. Where am I going wrong?
var count=0;
function rot(e){
count++;
var deg = count * 30;
e.style.transform = "rotate("+deg+"deg)";}
function rotat(){
count++;
var deg = count * 30;
this.style.transform = "rotate("+deg+"deg)";
}
.rectangle{
position: relative;
margin: 60mm;
width:90mm;
height:90mm;
border:5px solid #24ddff;
}
<div class = "rectangle" onclick="rot(this)"></div>
<button onclick="rotat()">Rotate</button>
<p id="demo"></p>

select div element . and use it in rotate function
var count=0;
const div = document.querySelector('div')
function rotat(){
count++;
var deg = count * 30;
div.style.transform = "rotate("+deg+"deg)";
}
.rectangle{
position: relative;
margin: 60px;
width:90px;
height:90px;
border:5px solid #24ddff;
}
<button onclick="rotat()">Rotate</button>
<div class = "rectangle"></div>

You should add id attribute to rectangle element that help you to recognize it within Javascript by getElementById
var count = 0;
function rot(e) {
count++;
var deg = count * 30;
e.style.transform = "rotate(" + deg + "deg)";
}
function rotat() {
const rectangle = document.getElementById("rectangle") //find rectangle element by id
count++;
var deg = count * 30;
rectangle.style.transform = "rotate(" + deg + "deg)";
}
.rectangle {
position: relative;
margin: 60mm;
width: 90mm;
height: 90mm;
border: 5px solid #24ddff;
}
<div class="rectangle" id="rectangle" onclick="rot(this)"></div>
<button onclick="rotat()">Rotate</button>
Or you can use class="rectangle" and find it by querySelector, but this way is not 100% safe because you may have multiple elements having rectangle class
var count = 0;
function rot(e) {
count++;
var deg = count * 30;
e.style.transform = "rotate(" + deg + "deg)";
}
function rotat() {
const rectangle = document.querySelector(".rectangle") //find rectangle element by id
count++;
var deg = count * 30;
rectangle.style.transform = "rotate(" + deg + "deg)";
}
.rectangle {
position: relative;
margin: 60mm;
width: 90mm;
height: 90mm;
border: 5px solid #24ddff;
}
<div class="rectangle" id="rectangle" onclick="rot(this)"></div>
<button onclick="rotat()">Rotate</button>

For some reasons "transform" did not work properly.
Try to use ".webkitTransform" instead ".transform".
Tip 2: Also try to bind the element by ID, not with Event.
Here some example:
<script type="text/javascript">
var rotatingDiv = document.getElementById("rotatingDiv");
rotatingDiv.style.webkitTransform = "rotate(-1.6deg)";
function transform()
{
var x=document.getElementById("element1");
rotatingDiv.style.webkitTransform = "rotate("+x.value+"deg)";
}
</script>

Related

CircleType text remove whitespace after rotateY

I'm having this code:
<div id="curvy">
This is the curved text
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/circletype#2.2.0/dist/circletype.min.js"></script>
<script>
const circleType = new CircleType(document.getElementById('curvy'));
circleType.dir(-1).radius(1100);
$( document ).ready(function() {
var counter = 1;
var deg = -40;
$($($('#curvy div').find('span')).get().reverse()).each(function (index, value ) {
/* var css = $(this).css('transform');
css = css + ' rotateY(-50deg)'; */
if(counter > 5) {
var text = $(this).html();
$(this).html('');
$(this).css('display','flex');
$(this).css('vertical-align','top');
console.log(text);
//$(this).html('');
var newElem = $('<span></span>').append(text);
newElem.appendTo($(this));
/* newElem.css('position','relative');
newElem.css('z-index',counter); */
newElem.css('vertical-align','top');
newElem.css('transform','rotateY('+ deg +'deg)');
deg = deg - 2.5;
}
//console.log(value);
counter = counter + 1;
});
});
</script>
<style>
html, body {
font-size: 30px;
}
</style>
This is working fine but after I start rotating each letter using rotateY in its own span, the parent span seems to add a white space in between that I want to get rid of.
Check jsfiddle
Well I was approaching it totally incorrectly.
The issue wasnt the spans, the padding or any margins but the translateX or rotate value.
Since CircleType was using the initial size of the letter when rendering the effect, the manipulations that I did through jQuery later weren't taken into account by it.
I had to save the matrix and then decide if I would go for an increment on the rotate value or on the translateX value. I chose the latter because it felt less complicated to play with. Since I need that the rotation will begin after a specific amount of character, I use the appropriate checks.
<div id="curvy">
Curved text
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/circletype#2.2.0/dist/circletype.min.js"></script>
<script>
const circleType = new CircleType(document.getElementById('curvy'));
circleType.dir(-1).radius(900);
$( document ).ready(function() {
var counter = 1;
var deg = -40;
var padding = 0;
$($($('#curvy div').find('span')).get().reverse()).each(function (index, value ) {
var css = $(this).css('transform').replace(/[^0-9\-.,]/g, '').split(',');
var x = css[12] || css[4];
var y = css[13] || css[5];
var a = css[0];
var b = css[1];
var angle = Math.atan2(b, a) * (180/Math.PI);
if(counter > 5) {
if(counter >= 12) {
padding = padding + 6 ;
} else
padding = padding + 4 ;
var text = $(this).html();
$(this).html('');
$(this).css('display','flex');
x = parseFloat(x) + padding;
$(this).css('transform', 'translateX('+x+'px) rotate('+angle+'deg)');
var newElem = $('<span></span>').append(text);
newElem.appendTo($(this));
newElem.css('transform','rotateY('+ deg +'deg)');
deg = deg - 2.5;
}
counter = counter + 1;
});
});
</script>
<style>
html, body {
font-size: 30px;
top: 50%;
left: 50%;
position: absolute;
}
</style>
Updated jsFiddle

For Loop not working and cloning Javascript

I've tried all sorts of things to figure out why my code isn't however, I can't seem to find out why. `
var numberOfFaces = 5;
var theleftside = document.getElementById ("leftSide");
var top_position = Math.floor((Math.random() * 400) + 1);
var left_position = Math.floor((Math.random() * 400) + 1);
var theRightSide = document.getElementById("rightSide");
function generatefaces () {
for (var i = 1; i < numberOfFaces; i++) {
var img = document.createElement("img");
img.src = "smile.png";
img.style.top = top_position + "px";
img.style.left = left_position + "px";
theleftside.appendChild(img);
}
}
<style media="screen">
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 2px solid black;
}
</style>
<h1>The Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
`
I am trying to generate 5 images (smiley faces) on the lefside div at different positions, then trying to clone it to the right hand side,
I'm new with JS, so hints and tips would be much appreciated.
Because you just implemented a function but did not call it. Try adding
generatefaces();
at the end.
Two fold firstly you need to, as burkay says, call the function generatefaces().
Secondly you need to create a second element for the right side using img.cloneNode(true) this creates a duplicate so you can then append that to the right side.
Also you are generating the random position outside of the loop so the same random position is used for each img you instead need to create a random position for every img by moving it inside the loop.
Example:
var numberOfFaces = 5;
var theleftside = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
// You need to call this function
generatefaces()
function generatefaces() {
for (var i = 1; i < numberOfFaces; i++) {
// Generate the new random position for each img
var top_position = Math.floor((Math.random() * 400) + 1);
var left_position = Math.floor((Math.random() * 400) + 1);
var img = document.createElement("img");
// The location of your face image
img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/54/Emojione_1F60E.svg/64px-Emojione_1F60E.svg.png";
img.style.top = top_position + "px";
img.style.left = left_position + "px";
// Creates a duplicate version of the image
var imgright = img.cloneNode(true);
theleftside.appendChild(img);
// Appends the duplicate image to the right side
theRightSide.appendChild(imgright);
}
}
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 2px solid black;
}
<h1>The Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
Hope this helps!

How to prevent element from exceeding his container borders

I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).
sometimes the square exceed his container border
How can I make sure that the square will never exceed his container?
function position() {
var positionTop = Math.random() * 100;
var positionLeft = Math.random() * 100;
var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
return position;
}
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.cssText = position();
}
#gameSpace {
width: 100%;
height: 470px;
background: blue;
margin: 0;
padding-top: 30px;
}
#playSpace {
width: 90%;
height: 90%;
margin: 0 auto;
margin-top: 10px;
border: 1px black solid;
}
#shape {
width: 100px;
height: 100px;
background-color: red;
}
<div id="gameSpace">
<div id="playSpace">
<!-- here we put the shape -->
<div id="shape"></div>
</div>
</div>
You need to set position: relative; to the parent element and position: absolute; to the shape element. Then use max min value for random where max is the parent width/height and subtract the shape width/height ...
This is snippet before update
function position() {
var playSpace = document.querySelector('#playSpace');
var shape = document.getElementById("shape");
var maxHeight = playSpace.offsetHeight - shape.offsetHeight;
var maxWidth = playSpace.offsetWidth - shape.offsetWidth;
var positionTop = Math.random() * (maxHeight - 0) + 0;
var positionLeft = Math.random() * (maxWidth - 0) + 0;
// think of this like so:
// var positionTop = Math.random() * (max - min) + min;
// more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;"
return position;
}
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.cssText = position();
}
#gameSpace {
width: 100%;
height: 470px;
background: blue;
margin:0;
padding-top: 30px;
}
#playSpace {
position: relative; /* add this line */
width: 90%;
height: 90%;
margin: 0 auto;
border: 1px black solid;
}
#shape {
width: 100px;
height: 100px;
background-color: red;
}
<div id="gameSpace">
<div id="playSpace">
<!-- here we put the shape -->
<div id="shape"></div>
</div>
</div>
Updated after comment
Not sure how you added the size() function but probably the problem was with using ...cssText that you overwrote the changes. So now I changed the code with passing the element to the functions and then only change the single CSS statements which need to be changed.
function position(element) {
var playSpace = document.querySelector('#playSpace');
var shape = document.getElementById("shape");
var maxHeight = playSpace.offsetHeight - shape.offsetHeight;
var maxWidth = playSpace.offsetWidth - shape.offsetWidth;
var positionTop = Math.random() * (maxHeight - 0) + 0;
var positionLeft = Math.random() * (maxWidth - 0) + 0;
// think of this like so:
// var positionTop = Math.random() * (max - min) + min;
// more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
element.style.position = 'absolute';
element.style.top = positionTop + "px";
element.style.left = positionLeft + "px";
}
function size(element) {
var sizeMath = (Math.random() * 200) + 50;
element.style.width = sizeMath + "px";
element.style.height = sizeMath + "px";
}
document.getElementById("shape").onclick = function() {
size(document.getElementById("shape"));
position(document.getElementById("shape"));
}
#gameSpace {
width: 100%;
height: 470px;
background: blue;
margin:0;
padding-top: 30px;
}
#playSpace {
position: relative; /* add this line */
width: 90%;
height: 90%;
margin: 0 auto;
border: 1px black solid;
}
#shape {
width: 100px;
height: 100px;
background-color: red;
}
<div id="gameSpace">
<div id="playSpace">
<!-- here we put the shape -->
<div id="shape"></div>
</div>
</div>
You can use a specify the range (min/max) in Math.random function and then use this function Math.floor(Math.random() * (max - min + 1)) + min; to limit the returned value of the random function between min and max.
maxTop : height of the container - height of shape
maxLeft : width of the container - width of shape
minTop : 0
minLeft : 0
You need to use position:absolute and px value on shape for this to work
See code snippet:
function position() {
var minTop = 0;
var maxTop = document.getElementById("playSpace").clientHeight - document.getElementById("shape").clientHeight;
var minLeft = 0;
var maxLeft = document.getElementById("playSpace").clientWidth - document.getElementById("shape").clientWidth ;
var positionTop = Math.floor(Math.random() * (maxTop - minTop + 1) + minTop);
var positionLeft = Math.floor(Math.random() * (maxLeft - minLeft + 1) + minLeft);
var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;"
return position;
}
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.cssText = position();
}
#gameSpace {
width: 100%;
height: 470px;
background: blue;
margin: 0;
padding-top: 30px;
text-align:center;
}
#playSpace {
width: 90%;
height: 90%;
border: 1px black solid;
position:relative;
display:inline-block;
}
#shape {
width: 100px;
height: 100px;
background-color: red;
}
<div id="gameSpace">
<div id="playSpace">
<!-- here we put the shape -->
<div id="shape"></div>
</div>
</div>
With CSS calc, limit the position inside playSpace area (you can use different units, here % and px).
Then with offsetTop/offsetLeft, get the real position of the square and avoid negative positions (when positionTop < 100px or positionLeft < 100px).
function position() {
var positionTop = Math.random() * 100;
var positionLeft = Math.random() * 100;
var position = "position:relative;top: calc(" + positionTop + "% - 100px);left: calc(" + positionLeft + "% - 100px);";
return position;
}
document.getElementById("shape").onclick = function() {
var shapeDiv = document.getElementById("shape");
shapeDiv.style.cssText = position();
var top = shapeDiv.offsetTop;// Result of calc(" + positionTop + "% - 100px) in px
if(top < 0) {
shapeDiv.style.top = '0px';
}
var left = shapeDiv.offsetLeft;// Result of calc(" + positionLeft + "% - 100px) in px
if(left < 0) {
shapeDiv.style.left = '0px';
}
}
Don't forget to add position: relative to #playSpace, to get offsetTop/left correct
#playSpace {
position:relative;/* mandatory */
}
You can get the parent element size, so that in your scirpt, use a condition to prevent the square to exceed.
function position() {
var maxWidth = document.getElementById("playSpace").offsetWidth;
var maxTop = document.getElementById("playSpace").offsetHeight;
var positionTop = Math.random() * 100;
var positionLeft = Math.random() * 100;
if (positionTop > maxTop) { positionTop = maxTop;)
if (positionLeft > maxWidth) { positionLeft = maxWidth;)
var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
return position;
}
I'm not sure if .offsetWidth and .offsetHeight works well, but you got the idea :)
By tweaking just a little your positionTop and positionLeft variable, I managed to keep the square inside. You just need to change the maximum % that it needs to have to not exceed the container. I found that 75% for the top and 80% for the left seems to be the max!
var positionTop = Math.floor(Math.random() * 75) ;
var positionLeft = Math.random() * 80;
Here's a fiddle
If you set the containing element to position: relative; and the inner element with position: absolute; the inner elements top left right and bottom properties will calculate from the borders of the containing element.
Here is a good source of css positioning.
In your case additional validation should be set to positionTop and positionLeft.
positionTop should be in the interval [( shapeHeight/2 ) - (100 - shapeHeight/2 ) ]
positionLeft should be in the interval [( shapeWidth/2 ) - (100 - shapeWeight/2 ) ]

Stop javascript "animation" onclick div

I'm a beginner in javascript and I'm trying to make a very simple game. I know that my code is not the best, but i want to make it working. I want to stop function nahoru() or make it move to the other way and after it touches the bottom of the page/100%, make it repeat.
<html>
<head>
<script>
function naloud() {
var elem = document.getElementById("krtek");
elem.style.top = '100%';
var eleme = document.getElementById("krtek2");
eleme.style.top = '100%';
var elemen = document.getElementById("krtek3");
elemen.style.top = '100%';
}
var pos = 100;
var los = 0;
function nahoru() {
var elemend = document.getElementById("batn");
elemend.style.opacity = '0';
var elem = document.getElementById("krtek");
var id = setInterval(frame, 30);
function frame() {
if (pos == 0) {
clearInterval(id);
document.write('<center>GAME OVER<br>YOUR SCORE: ' + skore +
'<br>Press F5 for restart.')
} else {
pos = pos - 1;
elem.style.top = pos + '%';
}
}
}
var skore = 0;
function pric() {
skore++;
document.getElementById("skore").innerHTML = "Skore: " + skore;
elem.style.top = '+100%';
}
</script>
<style>
.prvni {
position: absolute;
width: 10%;
height: 110%;
left: 10%;
background-color: brown;
}
.druhy {
position: absolute;
width: 10%;
height: 110%;
left: 45%;
background-color: brown;
}
.treti {
position: absolute;
width: 10%;
height: 110%;
left: 80%;
background-color: brown;
}
</style>
</head>
<body onload="naloud()">
<button onclick="nahoru()" id="batn">START</button>
<div id="skore">Skore: 0</div>
<div id="krtek" class="prvni" onclick="pric()"></div>
<div id="krtek2" class="druhy" onclick="pric()"></div>
<div id="krtek3" class="treti" onclick="pric()"></div>
</body>
</html>
Declare id outside nahoru function,
like here
var pos = 100;
var los = 0;
var id = null;
Set interval in nahoru function,
like this (important, remove var from here)
id = setInterval(frame, 30);
Now clear interval in pric function
like this
function pric(elem) {
skore++;
clearInterval(id);
document.getElementById("skore").innerHTML = "Skore: " + skore;
elem.style.top = '+100%';
}
Working https://jsfiddle.net/ee1bdL5k/
You need declare this var outside from function, for the pric function:
var elem, eleme, elemen;
function naloud() {
elem = document.getElementById("krtek");
elem.style.top = '100%';
eleme = document.getElementById("krtek2");
eleme.style.top = '100%';
elemen = document.getElementById("krtek3");
elemen.style.top = '100%';
}

Getting the wrong element in click handler with overlapping "circle" divs

I am trying dynamically add HTML elements with click handlers. When the click handler is activated it targets wrong element(it always target the outer circle). Where could be the problem?
(function() {
//selector, jQuery style
var $ = function(selector) {
return document.querySelector(selector);
}
//getting quantity of circles
var quantity = $('.circles').getAttribute('quantity');
//setting outer width/height for circles
$('.circles').style.width = (quantity * 50) + 4 + 'px';
$('.circles').style.height = (quantity * 50) + 4 + 'px';
//creating element for children
var childCircle = document.createElement('div');
childCircle.className = 'subCircle';
//click function for children
function onClick() {
this.attributes.style.value += 'border-color: red;'
alert(this.clientHeight);
}
//append sub circles
for (var i = 0; i < quantity; i++) {
$('.circles').appendChild(childCircle.cloneNode());
}
//iterate over .circles .subCircle and add onClick function for each subCircle and css aswell
var subCircle = $('.circles').getElementsByClassName('subCircle');
for (var i = 0; i < subCircle.length; i++) {
subCircle[i].onclick = onClick;
subCircle[i].style.width = ((i + 1) * 50) + 'px';
subCircle[i].style.height = ((i + 1) * 50) + 'px';
}
})();
.circles {
position: absolute;
}
.subCircle {
position: absolute;
border-radius: 50%;
transform: translateX(-50%) translateY(-50%);
border: 2px solid black;
top: 50%;
left: 50%;
}
<body>
<div class="circles" quantity=10></div>
</body>
Also on jsFiddle: https://jsfiddle.net/martin_borman/1srkL5bf/
The problem isn't this, which is actually getting set by the event callback mechanism just fine. It's that your largest circle is on top.
Changing the loop that sets the size lets you put the smaller circles on top:
for (var i = 0; i < subCircle.length; i++) {
subCircle[i].onclick = onClick;
subCircle[i].style.width = ((subCircle.length - i) * 50) + 'px';
subCircle[i].style.height = ((subCircle.length - i) * 50) + 'px';
}
The key bit there is (subCircle.length - i) * 50 rather than (i + 1) * 50.
I'd also use
this.style.borderColor = 'red';
rather than
this.attributes.style.value += 'border-color: red;'
Example:
(function() {
//selector, jQuery style
var $ = function(selector) {
return document.querySelector(selector);
}
//getting quantity of circles
var quantity = $('.circles').getAttribute('quantity');
//setting outer width/height for circles
$('.circles').style.width = (quantity * 50) + 4 + 'px';
$('.circles').style.height = (quantity * 50) + 4 + 'px';
//creating element for children
var childCircle = document.createElement('div');
childCircle.className = 'subCircle';
//click function for children
function onClick() {
this.style.borderColor = 'red';
alert(this.clientHeight);
}
//append sub circles
for (var i = 0; i < quantity; i++) {
$('.circles').appendChild(childCircle.cloneNode());
}
//iterate over .circles .subCircle and add onClick function for each subCircle and css aswell
var subCircle = $('.circles').getElementsByClassName('subCircle');
for (var i = 0; i < subCircle.length; i++) {
subCircle[i].onclick = onClick;
subCircle[i].style.width = ((subCircle.length - i) * 50) + 'px';
subCircle[i].style.height = ((subCircle.length - i) * 50) + 'px';
}
})();
.circles {
position: absolute;
}
.subCircle {
position: absolute;
border-radius: 50%;
transform: translateX(-50%) translateY(-50%);
border: 2px solid black;
top: 50%;
left: 50%;
}
<body>
<div class="circles" quantity=10></div>
</body>
Just add the z-index property for each circle
subCircle[i].style['z-index'] = subCircle.length-i;
Actually the larger circle is overlapping all the inner circle.

Categories