Function not defined at HTMLButtonElement.onclick - javascript

I was trying to make some controls to the box move to left, right, up and down. But when i make all the functions in the script tag, it get an error (in all the four onclick button):
Function not defined at HTMLButtonElement.onclick
in the lines that i make the button tag.
<html>
<button onclick = "leftmove()" id = "b1"> Left </button>
<button onclick = "rightmove()" id = "b2"> Right </button>
<button onclick = "upmove()" id = "b3"> Up </button>
<button onclick = "downmove()" id = "b4"> Down </button>
<h1 id = "box"></h1>
<style type = "text/css">
#box {
width: 50px;
height: 50px;
background-color: black;
}
<script>
var box = document.getElementById("box");
function leftmove() {
margin += 2;
box.style.marginLeft = margin + "px";
}
var box = document.getElementById("box");
function rightmove() {
margin -= 2;
box.style.marginLeft = margin + "px";
}
var box = document.getElementById("box");
function upmove() {
margin += 2;
box.style.marginTop = margin + "px";
}
var box = document.getElementById("box");
function downmove() {
margin -= 2;
box.style.marginLeft = margin + "px";
}
</script>
</html>

When using <script> tags like this, the functions and targeted tags have to be defined before usage. To make you example work you have to split you script tag to first define you functions and set the box variable later, after you have defined the corresponding tag. Also the margin variable is missing, I added is as zero but that's probably not how you want it. Working example:
<html>
<body>
<script>
var margin = 0;
function leftmove() {
margin += 2;
box.style.marginLeft = margin + "px";
}
function rightmove() {
margin -= 2;
box.style.marginLeft = margin + "px";
}
function upmove() {
margin += 2;
box.style.marginTop = margin + "px";
}
var box = document.getElementById("box");
function downmove() {
margin -= 2;
box.style.marginLeft = margin + "px";
}
</script>
<button onclick="leftmove()" id="b1"> Left </button>
<button onclick="rightmove()" id="b2"> Right </button>
<button onclick="upmove()" id="b3"> Up </button>
<button onclick="downmove()" id="b4"> Down </button>
<h1 id="box"></h1>
<style type="text/css">
#box {
width: 50px;
height: 50px;
background-color: black;
}
</style>
<script>
var box = document.getElementById("box");
</script>
</body>
</html>
A few notes aside the question:
A <div> might be more appropriate instead of the <h1> for the box
For rendering performance you would be better of using transform(x, y) instead of margins to move the box

Some JavaScript variables were created to manipulate the CSS indirectly. Other elements were also implemented to better understand the movements.
<html>
<style type = "text/css">
#box {
margin: 100px;
width: 50px;
height: 50px;
background-color: black;
}
</style>
<button onclick = "start()" id = "b0"> Start </button>
<button onclick = "leftmove()" id = "b1"> Left </button>
<button onclick = "rightmove()" id = "b2"> Right </button>
<button onclick = "upmove()" id = "b3"> Up </button>
<button onclick = "downmove()" id = "b4"> Down </button>
<div id="box"></div>
<script type="text/javascript">
var box = document.getElementById("box");
var margin = 10;
var marginX = 100;
var marginY = 100;
function start(){
box.style.margin = "100px";
marginX = 100;
marginY = 100;
}
function leftmove() {
marginX -= margin;
box.style.marginLeft = marginX + "px";
}
function rightmove() {
marginX += margin;
box.style.marginLeft = marginX + "px";
}
function upmove() {
marginY -= margin;
box.style.marginTop = marginY + "px";
}
function downmove() {
marginY += margin;
box.style.marginTop = marginY + "px";
}
</script>
</html>

Related

OnClick function to rotate a div element

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>

Im trying to create element by clicking button with position of moving existing element but it doesnt work

var arrow = document.getElementById("arrow");
function shot() {
var arrows = document.createElement("div");
document.body.appendChild(arrows);
arrows.style.backgroundColor = "black";
arrows.style.height = "80" + "px";
arrows.style.width = "3" + "px";
var arrowX = parseInt(document.arrow.style.left);
var arrowY = parseInt(document.arrow.style.top);
document.arrows.style.left = arrowX + "px";
document.arrows.style.top = arrowY + "px";
};
When I run it and click button which runs function shot it says it cannot read property "style" of undefined. It also spawns a new element on position it would spawn without any position defining.
Yep, my ids are correct.
Html:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="arrow"><div>
<button id="button" onclick="shot();"> Shot! </button>
</body>
</html>
CSS:
#arrow {
background-color: black;
height: 80px;
width: 1.5px;
position: relative;
left: 0px;
top: 0px;
}
Here is full project JS, which u dont need. Its not complete. There is button faster but it doesnt work, idk why. It should be archery game
var arrow = document.getElementById("arrow");
var arrowPos = -50;
var speed = 1000;
var speed2 = speed/100;
function arrow_move_right() {
arrowPos += 1;
arrow.style.left = arrowPos + "px";
if (arrowPos >= 280) {
return arrow_move_left()
}
else {
setTimeout(arrow_move_right, speed2);
};
};
function arrow_move_left() {
arrow = document.getElementById("arrow");
arrowPos -= 1;
arrow.style.left = arrowPos + "px";
if (arrowPos <= -50) {
return arrow_move_right()
}
setTimeout(arrow_move_left, speed2);
};
function faster() {
speed -= 100;
alert(speed)
}
function shot() {
var arrows = document.createElement("div");
document.body.appendChild(arrows);
arrows.style.backgroundColor = "black";
arrows.style.height = "80" + "px";
arrows.style.width = "1.5" + "px";
var arrowX = parseInt(arrow.style.left);
var arrowY = parseInt(arrow.style.top);
alert(arrowX);
alert(arrowY);
// arrows.style.left = arrowX;
// arrows.style.top = arrowY;
arrows.style.pos = "relative";
arrows.style.top = -50 + "px";
};
Hope this is what you are looking for!
var arrow = document.getElementById("arrow");
function shot() {
var arrows = document.createElement("div");
document.body.appendChild(arrows);
arrows.style.backgroundColor = "blue";
arrows.style.height = "80px";
arrows.style.width = "3px";
arrows.style.position = "absolute";
arrows.style.top = arrow.offsetTop + "px";
arrows.style.left = arrow.offsetLeft + "px";
};
#arrow {
height: 80px;
width: 3px;
background: black;
position: relative;
-webkit-animation: move 5s infinite; /* Safari 4.0 - 8.0 */
animation: move 5s infinite;
}
/* Styles for animating arrow */
/* Safari 4.0 - 8.0 */
#-webkit-keyframes move {
from {left: 0px;}
to {left: 400px;}
}
#keyframes move {
from {left: 0px;}
to {left: 400px;}
}
<div id="arrow"></div>
<button id="button" onclick="shot();"> Shot! </button>
Here is what I mean....
var arrow = document.getElementById("arrow");
function shot() {
var arrows = document.createElement("div");
document.body.appendChild(arrows);
arrows.style.backgroundColor = "black";
arrows.style.height = "80" + "px";
arrows.style.width = "3" + "px";
var arrowX = parseInt(arrow.style.left);
var arrowY = parseInt(arrow.style.top);
arrows.style.left = arrowX + "px";
arrows.style.top = arrowY + "px";
};
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="arrow"><div>
<button id="button" onclick="shot();"> Shot! </button>
</body>
</html>

Get the focused image element inside a contenteditable div

I need to modify a pasted image inside a contenteditable div: resize it proportionately, add borders, etc... Perhaps this can be achieved by adding a className that will alter the necessary CSS properties.
The problem is that I don't know how to reference the focused, i.e. the active, the clicked-upon image or any element for that matter.
This is the HTML that I am trying to use
<!DOCTYPE html>
<html>
<body>
<div contenteditable="true">This is a div. It is editable. Try to change this text.</div>
</body>
</html>
Using css, html and javascript
Your editable content should be inside a parent div with an id or class name, you can even have different divs for images and such.
Then it is as simple as having css like so:
#editableContentDiv img {
imgProperty: value;
}
Then you can have javascript like so:
function insertImage(){
var $img = document.querySelector("#editableContentDiv img");
$img.setAttribute('class','resize-drag');
}
Eventually if you have more than one img inside the same div you can use querySelectorAll instead of querySelector and then iterate through the img tags inside same div.
I beleive that should at least give you an idea of where to start with what you want.
Similar example
I found this gist that seems to have similar things to want you want but a bit more complicated.
function resizeMoveListener(event) {
var target = event.target,
x = (parseFloat(target.dataset.x) || 0),
y = (parseFloat(target.dataset.y) || 0);
// update the element's style
target.style.width = event.rect.width + 'px';
target.style.height = event.rect.height + 'px';
// translate when resizing from top or left edges
x += event.deltaRect.left;
y += event.deltaRect.top;
updateTranslate(target, x, y);
}
function dragMoveListener(event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.dataset.x) || 0) + event.dx,
y = (parseFloat(target.dataset.y) || 0) + event.dy;
updateTranslate(target, x, y);
}
function updateTranslate(target, x, y) {
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the position attributes
target.dataset.x = x;
target.dataset.y = y;
}
function insertImage() {
var $img = document.createElement('img');
$img.setAttribute('src', 'https://vignette.wikia.nocookie.net/googology/images/f/f3/Test.jpeg/revision/latest?cb=20180121032443');
$img.setAttribute('class', 'resize-drag');
document.querySelector(".container-wrap").appendChild($img);
var rect = document.querySelector(".container-wrap").getBoundingClientRect();
$img.style.left = rect.left;
$img.style.top = rect.top;
}
function dataTransfer() {
//cleanup
var $out = document.querySelector(".out-container-wrap");
while ($out.hasChildNodes()) {
$out.removeChild($out.lastChild);
}
//get source
var source = document.querySelector('.container-wrap')
//get data
var data = getSource(source);
//add data to target
setSource($out, data);
}
/**
* Get data from source div
*/
function getSource(source) {
var images = source.querySelectorAll('img');
var text = source.querySelector('div').textContent;
//build the js object and return it.
var data = {};
data.text = text;
data.image = [];
for (var i = 0; i < images.length; i++) {
var img = {}
img.url = images[i].src
img.x = images[i].dataset.x;
img.y = images[i].dataset.y;
img.h = images[i].height;
img.w = images[i].width;
data.image.push(img)
}
return data;
}
function setSource(target, data) {
//set the images.
for (var i = 0; i < data.image.length; i++) {
var d = data.image[i];
//build a new image
var $img = document.createElement('img');
$img.src = d.url;
$img.setAttribute('class', 'resize-drag');
$img.width = d.w;
$img.height = d.h;
$img.dataset.x = d.x;
$img.dataset.y = d.y;
var rect = target.getBoundingClientRect();
$img.style.left = parseInt(rect.left);
$img.style.top = parseInt(rect.top);
//transform: translate(82px, 52px)
$img.style.webkitTransform = $img.style.transform = 'translate(' + $img.dataset.x + 'px,' + $img.dataset.y + 'px)';
//$img.style.setProperty('-webkit-transform', 'translate('+$img.dataset.x+'px,'+$img.dataset.y+'px)');
target.appendChild($img);
}
//make a fresh div with text content
var $outContent = document.createElement('div')
$outContent.setAttribute('class', 'out-container-content');
$outContent.setAttribute('contenteditable', 'true');
$outContent.textContent = data.text;
target.appendChild($outContent);
}
interact('.resize-drag')
.draggable({
onmove: dragMoveListener,
inertia: true,
restrict: {
restriction: "parent",
endOnly: true,
elementRect: {
top: 0,
left: 0,
bottom: 1,
right: 1
}
}
})
.resizable({
edges: {
left: true,
right: true,
bottom: true,
top: true
},
onmove: resizeMoveListener
})
.resize-drag {
z-index: 200;
position: absolute;
border: 2px dashed #ccc;
}
.out-container-content,
.container-content {
background-color: #fafcaa;
height: 340px;
}
#btnInsertImage {
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://code.interactjs.io/interact-1.2.4.min.js"></script>
</head>
<body>
<button id="btnInsertImage" onclick="insertImage()">Insert Image</button>
<div class="container-wrap">
<div class="container-content" contenteditable="true">This is the content of the container. The content is provided along with the image. The image will be moved around and resized as required. The image can move within the boundary of the container.</div>
</div>
<button id="btnSubmit" onclick="dataTransfer()">Submit</button>
<div class="out-container-wrap">
</div>
</body>
</html>
Source
This is what I tried and it seems to be working - at least on my system, the snippet I made does not work unfortunately.
function getSelImg(){
var curObj;
window.document.execCommand('CreateLink',false, 'http://imageselectionhack/');
allLinks = window.document.getElementsByTagName('A');
for(i = 0; i < allLinks.length; i++)
{
if (allLinks[i].href == 'http://imageselectionhack/')
{
curObj = allLinks[i].firstChild;
window.document.execCommand('Undo'); // undo link
break;
}
}
if ((curObj) && (curObj.tagName=='IMG'))
{
//do what you want to...
curObj.style.border = "thick solid #0000FF";
}
}
<!DOCTYPE html>
<html>
<body>
<input type="button" onclick="getSelImg()" value="set img border">
<div contenteditable="true">This is a div.<br>
It is editable.<br>
Try to paste an image here:<br>
###########################<br>
<br>
<br>
<br>
###########################
</div>
</body>
</html>

update .style attributes with setInterval

I'm trying to move the position of a div element at set intervals however the setInterval method executes once and then stops. setInterval() doesn't update .style.transform repeatedly every 200 milliseconds as intended.
<!DOCTYPE html>
<html>
<head>
<title>Snake game</title>
<style type="text/css">
.container {
width: 500px;
height: 500px;
border: 2px solid black;
}
#snakehead {
width: 5px;
height: 5px;
background: pink;
position: relative;
left: 0px;
}
</style>
<script type="text/javascript" src="snake.js"></script>
</head>
<body>
<div class="container">
<div id="snakehead"></div>
</div>
</body>
</html>
Javascript: Ideally I'd also like to be able to move the snakehead in any direction with vx and vy. Anyway to put those values into .style.transform = translateX()?
function snakepos() {
var x = 0;
var y = 0;
var vx = 1;
var vy = 0;
return {
move: function() {
x += vx;
y += vy;
var snakehead = document.querySelector("#snakehead");
snakedhead.style.left = "5px";
}
};
}
window.onload = function() {
console.log("hi");
var container = document.querySelector(".container");
var snake = snakepos();
setInterval(function() {
snake.move();
}, 200);
}
I know this can be done much easier in jQuery with .css but I'd to how this can be done in vanilla javascript. Thank you in advance.
snakehead.style.left = (snakedhead.style.left + "5px");
or
snakehead.style.left = (snakedhead.style.left - "5px");
I'd recommend something in a style a bit more familiar to me:
function snakepos() {
this.x = 0;
this.y = 0;
this.vx = 1;
this.vy = 1;
this.snakehead = document.querySelector("#snakehead");
var me = this;
this.move = function() {
me.x += me.vx;
me.y += me.vy;
me.snakehead.style.top = me.y + "px";
me.snakehead.style.left = me.x + "px";
};
return this;
}
console.log("hi");
var container = document.querySelector(".container");
var snake = new snakepos();
setInterval(function() {
snake.move();
}, 200);
See fiddle: https://jsfiddle.net/theredhead/td8opb0b/1/

Creating Circles(div) and appending it to div#canvas

I am trying to create new circles as my pen hovers on window.
I am having issues where I cannot add circles to the page. It just hovers around. How would i be able to modify my code to add circles as it hovers.
<!doctype html>
<html>
<head>
<title> JavaScript Environment: Project </title>
<meta charset="utf-8">
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
#canvas {
background-color: yellow;
width: 100%;
height: 100%;
}
.pen {
position: absolute;
background-color: lightblue;
width: 10px;
height: 10px;
border-radius: 5px;
}
</style>
<script>
window.onload = function() {
function Circle(x, y) {
this.x = x;
this.y = y;
}
var canvas = document.getElementById("canvas");
canvas.onmousedown = function() {
mouseDown();
};
canvas.onmouseup = function() {
mouseUp()
};
canvas.onmousemove = function() {
mouseMove(event)
};
function mouseDown (){
console.log ("mouse down");
}
function mouseUp (){
console.log ("mouse up");
}
function mouseMove(e) {
var canvas = document.getElementById("canvas");
var pen = document.createElement("div");
var x = e.clientX;
var y = e.clientY;
var coor = "Coordinates: (" + x + "," + y + ")";
pen.setAttribute("class", "pen");
pen.style.left = x + "px";
pen.style.top = y + "px";
document.getElementById("canvas").innerHTML = coor;
canvas.appendChild(pen);
addCircles(x, y);
console.log("location # " + x + " : " + y);
}
function addCircles(x, y) {
var canvas = document.getElementById("canvas");
var circle = document.createElement("div");
circle.setAttribute("class", "pen");
circle.style.left = x + "px";
circle.style.top = y + "px";
canvas.appendChild(circle);
}
canvas.addEventListener("mouseMove", mouseMove, false);
};
</script>
</head>
<body>
<div id="canvas"></div>
</body>
</html>
The problem is in the line document.getElementById("canvas").innerHTML = coor;
Try adding a span <span id="canvasText"></span> inside of your canvas div and then changing the above line to document.getElementById("canvasText").innerHTML = coor;.
As it stands, you "reset" the contents of the canvas every time the mouse moves, so the circles are instantly removed from it. Reset only the span inside the canvas to keep the circles around.

Categories