How to make button randomly change position when clicked - javascript

When I click on the button, I would like the position of the button to change to a random location.
Here is what I have tried:
var b = document.querySelector("button");
b.addEventListener("click",change);
var i = Math.floor(Math.random()*500)+1;
var j = Math.floor(Math.random()*500)+1;
function change()
{
b.style.left = i+"px";
b.style.top = j+"px";
}
button{
margin-left: auto;
margin-right: auto;
display: block;
position: absoulte;
}
<button>
Hello World
</button>

Define i and j inside change() method so that it can be randomly updated when button is clicked.
Also, there is a typo in your code position: absoulte which should be corrected to absolute
var b = document.querySelector("button");
b.addEventListener("click",change);
function change()
{
var i = Math.floor(Math.random()*500)+1;
var j = Math.floor(Math.random()*500)+1;
b.style.left = i+"px";
b.style.top = j+"px";
}
button{
display: block;
position: absolute;
}
<button>abc</button>

HTML :-
<body>
<div class="ctr">
<button class="button" id="movingbutton">Button</button>
</div>
</body>
CSS:-
#movingbutton{
margin-left: auto;
margin-right: auto;
display: block;
position: absolute;
left : 20px;
top : 50px;
}
body{
width : 100%;
}
.ctr{
width : 100%;
height : 100%;
}
JS:-
var b = document.querySelector("#movingbutton");
b.addEventListener("click",change);
function change()
{
let i =Math.abs(Math.floor(Math.random()*window.innerWidth-55))
let j = Math.abs(Math.floor(Math.random()*window.innerHeight-21));
console.log('here' , i ,j , b.style.left , b.style.top);
b.style.left = i+'px';
b.style.top = j + "px";
}
If you want you can check here: Live example link
You need to add one more condition if that button goes outside window.innerWidth and window.innerHeight

You'll need to move the random calculation inside the change() function.
To keep the element within it's containing element you can use getBoundingClientRect(). (And account for the size of the button to avoid overlaps on the right and bottom using the same.)
const c = document.querySelector(".container");
const b = document.querySelector("button");
function change() {
const
{ width: cWidth, height: cHeight } = c.getBoundingClientRect(),
{ width: bWidth, height: bHeight } = b.getBoundingClientRect(),
i = Math.floor(Math.random() * (cWidth - bWidth)) + 1,
j = Math.floor(Math.random() * (cHeight - bHeight)) + 1;
b.style.left = i + "px";
b.style.top = j + "px";
}
b.addEventListener("click", change);
.container {
position: relative;
height: 50vh;
width: 50vw;
background-color: lightgray;
}
button{
position: absolute;
display: block;
}
<div class='container'>
<button type='button' id='shifty'>Click</button>
</div>

If you want to move randomly a button you can use simple .bind(). You can also move button when your mouse is moving in button area(without clicking it) .
Here are both codes:
Code for click
var b = document.querySelector("#movingbutton");
b.addEventListener("click",change);
function change()
{
let i = Math.floor(Math.random()*500)+1;
let j = Math.floor(Math.random()*500)+1;
console.log('here' , i ,j , b.style.left , b.style.top);
b.style.left = i+'px';
b.style.top = j + "px";
}
#movingbutton{
margin-left: auto;
margin-right: auto;
display: block;
position: absolute;
left : 20px;
top : 50px;
}
body{
width : 100%;
}
.ctr{
width : 100%;
height : 100%;
}
<body>
<div class="ctr">
<button class="button" id="movingbutton">Button</button>
</div>
</body>
Code for mousemove
var b = document.querySelector("#movingbutton");
b.addEventListener("mousemove",change);
function change()
{
let i = Math.floor(Math.random()*500)+1;
let j = Math.floor(Math.random()*500)+1;
console.log('here' , i ,j , b.style.left , b.style.top);
b.style.left = i+'px';
b.style.top = j + "px";
}
#movingbutton{
margin-left: auto;
margin-right: auto;
display: block;
position: absolute;
left : 20px;
top : 50px;
}
body{
width : 100%;
}
.ctr{
width : 100%;
height : 100%;
}
<body>
<div class="ctr">
<button class="button" id="movingbutton">Button</button>
</div>
</body>

Related

Appending an Element on Mousedown Into Specific Div Element Only

I am trying to add circles when the event mousedown is generated into the square-one (grey square) only. If the mouse hovers outside of the square-one, it should not insert any circles anywhere else such as square-two(green square).
Question: How can I set the limits for the circles such that they are only inserted within the square-one boundaries? Thank you for your help.
***********
JavaScript
***********
let count = 1
let greySquare = document.getElementById("square-one")
let mousePosition;
let circlesArray = []
document.addEventListener('mousedown', (event)=>{
let circle = document.createElement('div')
let circleHeight = 40
let circleWidth = 40
mousePosition = {
x: event.clientX,
y: event.clientY
}
circle.style.height = `${circleHeight}px`
circle.style.width = `${circleWidth}px`;
circle.style.borderRadius = "50%"
circle.style.backgroundColor = `#F0B27A`
circle.style.position = "absolute"
circle.style.left = (mousePosition.x - (circleWidth/2)) + "px"
circle.style.top = (mousePosition.y - (circleHeight/2)) + "px"
circle.style.lineHeight = `${circleHeight}px`
circle.style.display = 'flex';
circle.style.cursor = 'pointer'
circle.style.justifyContent = 'center';
circle.style.border = 'none'
circle.textContent = count++
greySquare.appendChild(circle)
circlesArray.push(circle)
})
********
HTML
********
<body>
<div class="container">
<div id="square-one"></div>
<div id="square-two"></div>
</div>
<script src="script.js"></script>
</body>
******
CSS
******
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
position: relative;
}
.container{
position: relative;
width: 100%;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
#square-one{
position: relative;
width: 300px;
height: 300px;
background-color: grey;
margin-right: 100px;
}
#square-two{
position: relative;
width: 300px;
height: 300px;
background-color: green;
}
When I use your code, the circles aren't being put where I actually click.
That is because you're using the mouse's position (which is relative to the page) to detect where you will put the circles, but then you append them to the
graySquare, which doesn't start at (0,0). If you append them to the .contaner instead, you'll be ok.
document.querySelector(".container").appendChild(circle)
Then regarding the set the limits for the circles such that they are only inserted within the square-one boundaries, you need to get the position (x and y), width and height of the squareOne and only proceed if the click occurs within those.
document.addEventListener('mousedown', (event)=>{
mousePosition = {
x: event.clientX,
y: event.clientY
}
let greySquarePosition = greySquare.getBoundingClientRect();
if(!(mousePosition.x>=greySquarePosition.left + window.scrollX&&
mousePosition.x<=greySquarePosition.left + window.scrollX + greySquarePosition.width&&
mousePosition.y>=greySquarePosition.top + window.scrollY&&
mousePosition.y<=greySquarePosition.top + window.scrollY + greySquarePosition.height))
return;
// ...
I used this to get the position of the div, and this to get its width and height (although they ended up being the same solution).
EDIT!
I kept thinking about this and there's a more obvious, more elegant solution (to me at least). You add the event listener to the graySquare and not the whole document.
greySquare.addEventListener('mousedown', (event)=> ...
Then you don't need the ugly part where you check if the mouse is within the limits.
You can even bind the same function to different squares. Check the updated snippet.
let count = 1
let greySquare = document.getElementById("square-one")
let greenSquare = document.getElementById("square-two")
let mousePosition;
let circlesArray = []
greySquare.addEventListener('mousedown', paintCircles.bind(null, '#F0B27A'), false);
greenSquare.addEventListener('mousedown', paintCircles.bind(null, '#fa0123'), false);
function paintCircles(color, event){
mousePosition = {
x: event.clientX,
y: event.clientY
}
let circle = document.createElement('div')
let circleHeight = 40
let circleWidth = 40
circle.style.height = `${circleHeight}px`
circle.style.width = `${circleWidth}px`;
circle.style.borderRadius = "50%"
circle.style.backgroundColor = `${color}`
circle.style.position = "absolute"
circle.style.left = (mousePosition.x - (circleWidth/2)) + "px"
circle.style.top = (mousePosition.y - (circleHeight/2)) + "px"
circle.style.lineHeight = `${circleHeight}px`
circle.style.display = 'flex';
circle.style.cursor = 'pointer'
circle.style.justifyContent = 'center';
circle.style.border = 'none'
circle.textContent = count++;
document.querySelector(".container").appendChild(circle)
circlesArray.push(circle)
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
position: relative;
}
.container{
position: relative;
width: 100%;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
#square-one{
position: relative;
width: 300px;
height: 300px;
background-color: grey;
margin-right: 100px;
}
#square-two{
position: relative;
width: 300px;
height: 300px;
background-color: green;
}
<body>
<div class="container">
<div id="square-one"></div>
<div id="square-two"></div>
</div>
</body>

Continually fade background box with each click of the fade button

Brand new to coding. Trying to get "fade" button to fade a little more each time I click it.
I have used this code to grow and shrink the box and I was trying to do the same thing for the opacity:
document.getElementById("growbutton").addEventListener("click", function() {
var growVariable = 10;
var newValueHeight = parseInt(document.getElementById("box").style.height)
document.getElementById("box").style.height = newValueHeight + growVariable + "px";
var newValueWidth = parseInt(document.getElementById("box").style.width)
document.getElementById("box").style.width = newValueWidth + growVariable + "px";
});
document.getElementById("fadebutton").addEventListener("click", function() {
var opVariable = .2;
var newOpValue = parseInt(document.getElementById("box").style.opacity)
document.getElementById("box").style.opacity = newValueHeight - opVariable;
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px"></div>
<button id="fadebutton">Fade</button>
<button id="growbutton">Grow</button>
Can you tell me what I'm missing so the box fades .2 with each click?
Your existing code produces the error: Uncaught ReferenceError: newValueHeight is not defined. There were a few issues:
You were referencing newValueHeight instead of newOpValue by accident.
parseInt() will return an integer, i.e., if the current opacity is 0.8, parseInt(0.8) returns 1. You need to use parseFloat() to get a floating point back.
Initially, style.opacity is undefined because it has not been set yet. You should use opValue = ... || 1 so that it defaults to 1 if not yet set.
let box = document.getElementById('box'),
fadeBtn = document.getElementById('fadebutton'),
growBtn = document.getElementById('growbutton');
growBtn.addEventListener('click', function() {
let growVariable = 10,
boxHeight = parseInt(box.style.height),
boxWidth = parseInt(box.style.width);
box.style.height = boxHeight + growVariable + "px",
box.style.width = boxWidth + growVariable + "px";
});
fadeBtn.addEventListener("click", function() {
let opVariable = .2,
opValue = parseFloat(box.style.opacity) || 1;
box.style.opacity = opValue - opVariable;
});
<div id="box" style="height: 100px; max-height: 600px; min-height: 5px; width:100px; max-width: 600px; min-width: 5px; background-color:orange; margin:1rem"></div>
<button id="fadebutton">Fade</button>
<button id="growbutton">Grow</button>
You need to use parseFloat when dealing with non-whole numbers or with decimal points as parseInt returns an integer or a whole number
document.getElementById("fadebutton").addEventListener("click", function() {
//var opVariable = .2;
let box = document.getElementById("box")
let currentOpacity = parseFloat(box.style.opacity)
box.style.opacity = currentOpacity - .2
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px;opacity:1"></div>
<button id="fadebutton">
Fade
</button>
document.getElementById("fadebutton").addEventListener("click", function() {
//var opVariable = .2;
let box = document.getElementById("box")
let currentOpacity = parseFloat(box.style.opacity)
box.style.opacity = currentOpacity - .2
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px;opacity:1"></div>
<button id="fadebutton">
Fade
</button>
If you just want to fade the image onclick, you can simply decrement the style.opacity property. Something like this:
const box = document.querySelector('#box');
document.addEventListener('click', e => {
if (e.target.id === 'fadebutton') {
if (box.style.opacity > 0) {
box.style.opacity -= .2;
}
}
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px; opacity: 1"></div>
<button id="fadebutton">Fade</button>

how to make a box reach the edge of a bigger box

javascript beginner here! so i'm trying to do a box(that is inside a larger box) move from the top to the edge of the box. Here's the code:
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5);
function boxmove() {
if (loc == 320) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox">
<div id="boxcont"></div>
</div>
<button id="boxbtn">Move the box</button>
The problem is that the small box doesn't exactly ends up at the edge, it goes more to the right. I tried doing
boxcont.style.left = (loc - 0.5) + "px";
but doesn't work. pretty sure the solution is simple but as a newbie here it's confusing me :p. Oh and i also tried doing ++ to the 0.5 and Number(0.5) so it reads it as a decimal but still doesn't work!
the big gray box is not set to the correct height and width that corresponds with the small red box's movement. You have it going down 1 and to the right 1 every 5 however, your actually going across a rectangle, not a square. set your width and height the same for the gray box and slightly adjust the stopping point to a little bit less.
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5); // every five milliseconds
function boxmove() {
if (loc == 290) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox" style = "height: 320px; width: 320px">
<div id="boxcont" ></div>
</div>
<button id="boxbtn">Move the box</button>
if (loc == 270) {
instead of
if (loc == 320) {
Gets you there.
300px is the width of the containing div and the moving div is 30px wide so 300-30=270px
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5);
function boxmove() {
if (loc == 270) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox">
<div id="boxcont"></div>
</div>
<button id="boxbtn">Move the box</button>

div transform is not working on mouseover with javascript

I have a parent div and a child div. Now the function I want to perform is that when the coordinate of mouse x and y of the parent div is greater than 413 and 10, the child div should rotate. But its not working. I want to do it with JavaScript. So please tell me what is the mistake here.
By the way I am not getting any error in console.
window.onload = function() {
var test = document.getElementsByClassName("parent-div");
for (var i = 0; i < test.length; i++) {
test[i].addEventListener("mousemove", function(event) {
var x = event.clientX;
var y = event.clientY;
console.log(x + " " + y);
if (x > 413 && y > 10) {
for (var i = 0; i < test.length; i++) {
test[i].mousemove = function(idx) {
this.classList.toggle("rotated");
if (idx < test.length - 1) test[idx + 1].classList.toogle("rotated");
}.bind(test[i], i);
}
}
}, false);
}
};
body {
background-color: #aaa;
}
.parent-div {
width: 500px;
height: 500px;
background-color: yellow;
display: flex;
justify-content: space-around;
perspective: 500px;
}
.child-div {
width: 250px;
height: 250px;
margin-top: 100px;
background-color: blue;
}
div.rotated>div.child-div {
transform: rotateY(45deg);
}
<body>
<div class="parent-div">
<div class="child-div"></div>
</div>
<script type="text/javascript" src="script.js"></script>
</body>

How to rollover text on images dynamically using javascript/jquery

I am new to web development but highly fascinated by it. So, basically I am creating a light-box where thumbnails of images will be appear on screen and they will appear bigger in size when user clicks over them. Now, I want when user hovers over the gallery images/thumbnails then some text should appear over the current image with may be some animation or basically mouser-hover should cause some event to happen but I am unable to do it. Text should be added dynamically or may be previously stored in an array or something of that sort. Please have a look at my code and tell me how to modify it in order to achieve such effect and if you know a better and easier way to do so then feel free to share. Thank you so much!!
HTML:
<div class="gallery">
<ul id="images"></ul>
<div class="lightbox">
<div class='limage'>
</div>
<div class='left'>
</div>
<div class='right'>
</div>
<div class='close'>
x
</div>
</div>
</div>
JAVASCRIPT:
var gallery_slider = new Array();
gallery_slider[0] = "im1.jpg";
gallery_slider[1] = "im2.jpg";
gallery_slider[2] = "im3.jpg";
function displayAllImages() {
var i = 0,
len = gallery_slider.length;
for (; i < gallery_slider.length; i++) {
var img = new Image();
img.src = gallery_slider[i];
img.style.width = '200px';
img.style.height = '120px';
img.style.margin = '3px';
img.style.cursor = 'pointer';
document.getElementById('images').appendChild(img);
}
};
$(function() {
displayAllImages();
});
$(function() {
$('img').click(function() {
var hell = (this).src;
display(hell);
});
});
function display(hello) {
$('header').css('display', 'none'); /*for some other purposes*/
$('.limage').html("<img src=" + hello + " >");
$('.lightbox').css("display", "block");
$('.lightbox').fadeIn();
$('.right').click(function() {
var im = new Array();
var x;
var p;
for (x = 0; x < gallery_slider.length; x++) {
im[x] = gallery_slider[x];
}
for (p = 0; p < im.length; p++) {
if (im[p] == hello) {
break;
} else {
continue;
}
}
if (p >= (im.length - 1)) {
p = -1;
}
$('.limage').fadeOut(0);
$('.limage').html("<img src= " + im[p + 1] + ">");
$('.limage').fadeIn(500);
hello = im[p + 1];
});
$('.left').click(function() {
var im = new Array();
var x;
var p;
for (x = 0; x < gallery_slider.length; x++) {
im[x] = gallery_slider[x];
}
for (p = 0; p < im.length; p++) {
if (im[p] == hello) {
break;
} else {
continue;
}
}
if (p == 0) {
p = (im.length);
}
$('.limage').fadeOut(0);
$('.limage').html("<img src= " + im[p - 1] + ">");
$('.limage').fadeIn(500);
hello = im[p - 1];
});
$('.close').click(function() {
$('.lightbox').fadeOut();
$('header').css('display', 'block'); /*for some other purposes*/
});
};
CSS:
.gallery {
width: 100%;
height: 400px;
overflow: hidden;
margin: auto;
}
.gallery ul {
list-style: none;
}
.lightbox {
background-color: rgba(0, 0, 0, 0.3);
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
z-index: 106;
}
.close {
color: #fff;
border: 1px solid #fff;
border-radius: 100px;
background-color: #000;
position: absolute;
top: 10px;
right: 20px;
padding: 10px;
font-family: firstfont;
font-size: 30px;
z-index: 101;
cursor: pointer;
}
.close:hover {
background-color: #ebebeb;
color: #000;
}
.left {
width: 50%;
height: 100%;
position: absolute;
top: 0;
left: 0;
cursor: pointer;
}
.right {
width: 50%;
height: 100%;
position: absolute;
top: 0;
right: 0;
cursor: pointer;
}
.limage {
position: relative;
margin: auto;
top: 17%;
left: 15%;
max-width: 90%;
max-height: 90%;
}
There might be some bugs in coding. Watch out.
This code is working for displaying images as thumbnails as a matrix and as slider in lightbox when clicked upon them. I am not able to figure out how to add hover functionality to initial thumbnails.
Jsfiddle :
http://jsfiddle.net/psd6cbd7/1/
I'd suggest putting a div inside the image div containing the text and then using CSS to hide/show it.
HTML:
<div class="gallery">
<ul id="images"></ul>
<div class="lightbox">
<div class='limage'>
<div class=".caption">Caption here</div>
</div>
<div class='left'>
</div>
<div class='right'>
</div>
<div class='close'>
x
</div>
</div>
</div>
CSS:
.limage { position: relative; }
.caption { display: none; }
.limage:hover .caption { display: block; position: absolute;}
Why you using array to store the images? Anyways, assume that you still using array, below is some example code that you want try:
HTML:
<ul id="images">
</ul>
<!-- assume this is the place that you want to display the caption -->
<div id="caption"></div>
Javascript:
var images = new Array();
images[0] = "p1.png";
images[1] = "p2.png";
images[2] = "p3.png";
images[3] = "p4.png";
var captions = new Array();
captions[0] = "Picture 1";
captions[1] = "Picture 2";
captions[2] = "Picture 3";
captions[3] = "Picture 4";
var x = $("#images");
var y = $("#caption");
const prefix = "image-";
if you are using HTML5:
for (var i = 0; i < images.length; i++) {
x.append("<img class='roll' src='" + images[i] + "' data-caption='" + captions[i] + "'>");
}
$(".roll").mouseover(function(){
//do whatever effect here when mouse over
y.html($(this).attr("data-caption"));
});
If you want to backward compatible:
for (var i = 0; i < images.length; i++) {
x.append("<img id='" + prefix + i + "' class='roll' src='" + images[i] + "'>");
}
$(".roll").mouseover(function(){
//do whatever effect here when mouse over
var index = $(this).attr("id").substring(prefix.length);
y.html(captions[index]);
});
Hope that this will help.

Categories

Resources