I worked on a mini project that works when I click on the mouse the screen populates with numerous circles with each click. I am trying to do the same thing, however, the difference is when the spacebar is pushed for it to do the same thing.
For some reason the code I have is not working I am even console logging and see nothing and I do not understand why. Some guidance would be appreciated.
Here is my html:
<!DOCTYPE html>
<html>
<head>
<title>CircleMaker</title>
<link href="main.css" rel="stylesheet">
</head>
<body>
<div id="ball"></div>
</body>
<script src="mainn.js"></script>
</html>
css
html{
box-sizing: border-box;
}
*, *::before, *::after{
box-sizing: inherit;
}
#ball{
width: 200px;
height: 200px;
top: 200px;
left: 200px;
background-color: red;
border-radius: 100px;
}
Javascript
var circle = document.getElementById('ball');
circle.addEventListener('keydown', circleMultiplier);
function circleMultiplier(e){
e.preventDefault();
console.log(e.keyCode);
if (e.key === 32){
var divsize = ((Math.random()*100) + 50).toFixed();
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
var posx = (Math.random() * (document.body.clientWidth - divsize).toFixed());
var posy = (Math.random() * (document.body.clientWidth - divsize).toFixed());
var newDiv = document.createElement('div');
newDiv.style.cssText = 'top:'+posx+'px; left:'+posy+'px; position:absolute; width: 200px; height: 200px;background-color:' +color+ '; border-radius: 100px;';
document.body.appendChild(newDiv);
}
}
When I hit the spacebar it should populate like the following image:
This code works for when I click the mouse:
var circle = document.getElementById('ball');
circle.addEventListener('click', circleMultiplier);
function circleMultiplier(){
var divsize = ((Math.random()*100) + 50).toFixed();
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
var posx = (Math.random() * (document.body.clientWidth - divsize).toFixed());
var posy = (Math.random() * (document.body.clientWidth - divsize).toFixed());
var newDiv = document.createElement('div');
newDiv.style.cssText = 'top:'+posx+'px; left:'+posy+'px; position:absolute; width: 200px; height: 200px;background-color:' +color+ '; border-radius: 100px;';
document.body.appendChild(newDiv);
}
You can not listen to a keyboard event on a div. The click is happening on the div itself so it executes the corresponding callback function.
For your use case it makes more sense to attach the listener it the document itself.
For example.
document.addEventListener('keyup', function(e){console.log(e.keyCode)});
Related
So i've got hammer.js swipe to work on my div. the swipe region looks like this
https://imgur.com/ncW4nDB
so basically, i want the orange area to be able to swipe left/right and when it reaches the end (on both sides), it halts swiping.
the script and etc :
var containerDiv = document.getElementById('list-container');
var listDiv = document.getElementById('train-line-list');
// Create a manager to manager the element
var manager = new Hammer.Manager(listDiv);
// Create a recognizer
var Swipe = new Hammer.Swipe();
// Add the recognizer to the manager
manager.add(Swipe);
// Declare global variables to swiped correct distance
var deltaX = 0;
var deltaY = 0;
// Subscribe to a desired event
manager.on('swipe', function(e) {
deltaX = deltaX + e.deltaX;
var direction = e.offsetDirection;
var translate3d = 'translate3d(' + deltaX + 'px, 0, 0)';
if (direction === 4 || direction === 2) {
e.target.innerText = deltaX;
e.target.style.transform = translate3d;
}
});
<div id="list-container">
<div id="train-line-list">
<img id="" src="">
<img id="" src="">
</div>
#list-container{
z-index: 10;
position:fixed;
top:60%;
left:0;
width:100%;
height:40%;
}
#train-line-list{
width: 95%;
height: 95%;
top: 2%;
margin: 0 auto;
position: relative;
}
like i said, the swiping sort of works but the images disappear. why does this happen and how can i fix it? Also, the swiping is not very "reactive" in a way, like its slow. not natural. is there an alternative? or a better way to implement? Also, just realized, the images can be swiped as well ?? how do i "lock" the images. i just want the container of the images to be swiped.
Here is a working example
<html>
<head>
<style>
#box {
background-color: red;
height: 100px;
width: 100px;
margin-right: 10px;
}
#collection {
display: flex;
flex-direction: horizontal;
}
#container {
display: flex;
background-color: aqua;
padding: 50px 0px 50px 0px;
overflow: scroll;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.js"></script>
</head>
<body>
<div id="container">
<div id="collection">
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
</div>
</div>
<script>
var container = document.getElementById("container");
var content = document.getElementById("collection");
var hammer = new Hammer(container);
var initialX = 0;
var deltaX = 0;
var offset = initialX + deltaX;
hammer.on("panleft panright", function(ev) {
deltaX = ev.deltaX;
offset = initialX + deltaX;
container.scroll(-offset, 0);
});
Hammer.on(container, "mouseup", function(e) {
initialX = offset;
});
</script>
</body>
</html>
You could replace the squares with your images.
I've created a program that randomly spawns a span (in the form of a circle). I want to change the onClick of the previous span class when clicked on.
I've already attempted to set the id of the new span element to something that creates recursively (span.id = "a" + t; t++;) or something like that.
<!doctype html>
<link href="https://fonts.googleapis.com/css?
family=Montserrat" rel="stylesheet">
<link rel="icon" type="image/jpg" href="/vNidjVg-
_400x400.jpg"/>
<style>
body{
background-color: #010417;
font-family: 'Montserrat', sans-serif;
}
#keyframes a{
0% {opacity: 0;}
100%{opacity: 1;}
}
button{
background-color: #010417;
border-radius: 10px;
border: 4px solid white;
color: white;
padding: 10px 26px;
font-size: 20px;
}
</style>
<div id="myDIV">
<script>
document.title = prompt("I don't know what to make the
document's title, so what do you want it to be called?");
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
var but = 2;
var x = 0
function button(){
if(but === 2){
myFunction();
but = 0;
}else{}
}
var t = 0;
var q = -1;
function myFunction() {
var para = document.createElement("SPAN");
para.style.position = "absolute";
x = getRndInteger(0, (window.innerWidth - 60))
para.style.left = x + "px"
var p = getRndInteger(0, (window.innerHeight - 60))
para.style.top = p + "px"
para.style.display = "inline-block;"
para.style.height = "50px"
para.style.width = "50px"
para.style.backgroundColor="red"
para.style.borderRadius = "50px"
para.style.border = "1px solid black"
para.style.animation = "1s a linear"
para.id = "a" + t;
document.getElementById("a" + q).onclick=f
q++
t++;
para.onclick=myFunction
document.getElementById("myDIV").appendChild(para);
}
function f(){}
</script>
</div>
<center>
<button class="1" id="button" onClick="button();">Start</button></center>
I expect the output of this to be the previous span class to be disabled (onclick set to f())
Firstly, you should define as much of the style of your elements as possible in CSS instead of defining it in Javascript.
Secondly, when a onclick is called in JS, the first parameter of the function should be event which is a representation of the click event that just appeared. Here in the onclick you can get the clicked element with event.toElement which allows you to redefine onclick.
I think what you are trying to do should look like something like this :
var container = document.getElementById("container");
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
function spawn() {
var span = document.createElement("SPAN");
span.style.left = getRndInteger(30, (container.offsetWidth - 30)) + "px";
span.style.top = getRndInteger(30, (container.offsetHeight - 30)) + "px";
span.onclick = fA;
container.appendChild(span);
}
function fA(event) {
var span = event.toElement
alert("first click here");
span.onclick = fB;
}
function fB(event) {
alert("second click here");
}
div#container {
width: 300px;
height: 300px;
}
div#container span {
width: 30px;
height: 30px;
position: absolute;
border-radius: 100%;
background-color: red;
}
<button onclick="spawn()">Spawn a span</button>
<div id="container"></div>
My code is for a website where when you press the movement button the two squares will move and if you press the change colour button both squares will alternate colours. The shapes do these actions at the same time. However, only one square does this while the other does nothing... please help?
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: CadetBlue;
}
div#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: Maroon;
}
</style>
<style>
#containertwo {
width: 400px;
height: 400px;
position: relative;
background: CadetBlue;
}
div#animatetwo {
width: 50px;
height: 50px;
position: absolute;
left: 350px;
top: 0px;
background-color: Olive;
}
</style>
<body>
<p>
<button onClick="myMove()">Movement</button>
</p>
<p>
<button onClick="button_click()">Change Colour</button>
</p>
<div id ="container">
<div id ="animate"></div>
<div id ="animatetwo"></div>
</div>
<div id="box" onClick="button_click();"></div>
<script>
var colors = ["Maroon","Olive"];
function button_click() {
var box = document.getElementById("animate");
var background_color = box.style.backgroundColor;
var i = colors.indexOf(background_color);
if (i === colors.length-1) {
i = -1;
}
animate.style.backgroundColor = colors[i+1];
}
</script>
<div id="box" onClick="myMove();"></div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 1);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
<div id="box" onClick="button_click();"></div>
<script>
var colorstwo = ["Maroon","Olive"];
function button_clicktwo() {
var box = document.getElementById("animatetwo");
var background_color = box.style.backgroundColor;
var i = colorstwo.indexOf(background_color);
if (i === colorstwo.length-1) {
i = -1;
}
animatetwo.style.backgroundColor = colorstwo[i+1];
}
</script>
<div id="box" onClick="myMove();"></div>
<script>
function myMovetwo() {
var elem = document.getElementById("animatetwo");
var pos = 0;
var id = setInterval(frame, 1);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
</body>
</html>
Ok... I'll talk about the problem you're having first, then I'll try to give you some advice.
1) First of all upon clicking the "Movement" button you're only calling the myMove() function which is only responsible for moving the animated div, as you select it with:
var elem = document.getElementById("animate");
So if you desire to move both at the same time make sure you're activating the right functions, since I imagine you wanted to call myMovetwo() at the same time perhaps you could do:
function move() {
myMove();
myMovetwo();
}
That way you would call move() and both calls will run.
2) Now about your code, you should really consider isolating the different aspects of your page, and by that I mean isolating CSS, HTML and JavaScript, you can do that using the <link> tag to import your styles and the <script src="path"></script> tag to include your javascript code.
The other advice would be to remove onclick from your html tags and get the click event from your javascript code.
There are some great sources to learn this basics concepts, perhaps codecademy is a great one for starters https://www.codecademy.com/courses/html-javascript-css/0/1
Cheers!
I am new in web development , I am working on DnD (drag & drop) , I make a small code which can drag and drop only one element any where on page . But Now I am want set their properties from UI for example see that link : https://www.draw.io/
Anyone can help me please . Thanks !
code is following which I did :
<!DOCTYPE HTML>
<html>
<title></title>
<style>
#dragme {
position: absolute;
left: 0;
top: 0; /* set these so Chrome doesn't return 'auto' from getComputedStyle */
background: rgba(255,255,255,0.66);
border: 2px solid rgba(0,0,0,0.5);
border-radius: 4px; padding: 8px;
}
</style>
<body>
<div style="height:700px;width:100%;border:2px solid green;background-color:#60CEFB;">
<input type="button" draggable="true" id="dragme" style="color:#fff;width70px;height:50px;border:2px solid white;background-color:black;box-shadow:1px 1px 1px 1px grey;" value="Go India" name="button" />
<script>
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain",
(parseInt(style.getPropertyValue("left"),10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"),10) - event.clientY));
}
function drag_over(event) {
event.preventDefault();
return false;
}
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementById('dragme');
dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
event.preventDefault();
return false;
}
var dm = document.getElementById('dragme');
dm.addEventListener('dragstart',drag_start,false);
document.body.addEventListener('dragover',drag_over,false);
document.body.addEventListener('drop',drop,false);
</script>
</div>
</body>
</html>
I have posted my problem at http://jsfiddle.net/ugnf4/ as it would be make it easier.
Below is my html / javascript code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="mainContainer">
<div id="pageContainer" style="background: #cdcdcd;"></div>
</div>
<style>
BODY {
margin: 0px;
padding: 0px;
}
#pageContainer {
position: relative;
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
border: 1px solid #000000;
}
#mainContainer {
width: 100%;
overflow: hidden;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script type="text/javascript">
$(document).ready(function() {
setHeight();
$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
});
</script>
</body>
</html>
Currently #mainContainer div has overflow hidden as i dont want to show scroll bars and #pageContainer div (inner div) is scaled at 1.37 using css3, as in certain cases based on screen / browser width height #pageContainer's content would be hidden because of overflow hidden.
I want to code javascript so that if somebody moves cursor in #mainContainer, based on position of mouse X and Y co-ordinates I would like to move #pageContainer so that similar position of #pageContainer would be visible (I hope it is clear).
I m having problem as I m using -webkit-transform-origin, unable to understand how to move #pageContainer around with respect to mouse co-ordinates of #mainContainer.
UPDATE:
I m looking something like what happens in issuu.com website when you open an ebook and zoom it more than the browser size (Should make it more clear)
I m looking for algo or pointer how to achieve it (how to calculate it) not necessarily a working script.
How can this be achieved.
Below is working html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="mainContainer">
<div id="pageContainer" >
<div id="pageContainerInner"style="background: #cdcdcd;">
</div>
</div>
<style>
BODY {
margin: 0px;
padding: 0px;
}
#pageContainer {
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
}
#mainContainer {
width: 100%;
overflow: hidden;
}
#pageContainerInner {
position: relative;
width: 1218px;
height: 774px;
border: 1px solid #000000;
top: 0;
left: 0;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script type="text/javascript">
var pageWidth = 1220;
var pageHeight = 776;
var scale = 1.37;
var scaledDelta = 5; //Percentage mouse position approximation
$(document).ready(function() {
setHeight();
$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
// Calculate the offset of scaled Div
var offsetX = $('#pageContainer').offset().left;
var offsetY = $('#pageContainer').offset().top;
// Calculate div origin with respect to screen
var originX = (-1 * offsetX) / scale;
var originY = (-1 * offsetY) / scale;
var wWdt = $(window).width();
var wHgt = $(window).height();
// Now convert screen positions to percentage
var perX = e.pageX * 100 / wWdt;
var perY = e.pageY * 100 / wHgt;
// Div content which should be visible
var pageX = perX * pageWidth / 100;
var pageY = perY * pageHeight / 100;
// Calculate scaled divs new X, Y offset
var shiftX = (originX - pageX) + (e.pageX / scale);
var shiftY = (originY - pageY) + (e.pageY / scale);
$('#pageContainerInner').css({'left': shiftX+'px', 'top': shiftY+'px'});
});
</script>
</body>
</html>
Hope this will help others.
I have posted a probable solution at http://jsfiddle.net/PYP8c/.
Below are the modified styles for your page.
BODY {
margin: 0px;
padding: 0px;
}
#mainContainer {
width: 100%;
overflow: hidden;
position: relative;
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
border: 1px solid #000000;
}
#pageContainer {
position:absolute;
top:0px;
}
This is the javascript code for the same.
$(document).ready(function() {
//setHeight();
//$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
var contentHeight = $("#pageContainer").height();
var minTop = 774 - contentHeight;
if(minTop>0)
minTop = 0;
var currTop = ((e.pageY-10)/774.0)*(minTop);
document.getElementById("pageContainer").style.top = currTop+'px';
});
Its just a demo on how you could get the text to move based on the mouse coordinates.
You could make a lot of changes, like adding a scrollbar that fades which gives the user a feedback about how much content is still available in both the vertical directions.
Also I have used hard coded values for height, but in your final version I would recommend you get the height of the mainContainer division dynamically.