The code here should take the element and move it to the left or right. However, the image is still in place.
var posX = 100;
document.getElementById("ship").addEventListener("keydown", moveShip);
function moveShip(event) {
if (event.key == "ArrowLeft") {
posX -= 2;
} else if (event.key == "ArrowRight") {
posX += 2;
}
}
HTML of the code is very basic, nothing much has been added here
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title>ship</title>
</head>
<body>
<img id="ship" src="spaceship.png" />
<canvas id="myCanvas"></canvas>
<script src="extensions.js"></script>
<script src="main.js"></script>
</body>
</html>
The CSS of the code is here
canvas{
border: 1px, solid, black;
}
html{
background-color: black;
}
#ship{
width: 100px;
}
You should give the image a relative position and set the left CSS property to move it.
<img id="ship" src="spaceship.png" style="position: relative;"/>
<script>
var posX = 100;
var ship = document.getElementById("ship");
ship.style.left = posX;
ship.addEventListener("keydown", moveShip);
function moveShip(event) {
if (event.key == "ArrowLeft") {
posX -= 2;
} else if (event.key == "ArrowRight") {
posX += 2;
}
ship.style.left = posX;
}
</script>
Related
I need to console log x coordinate every 1 sec when pointer is on picture but I have no idea how to update "event" from the js code.
function onPic(event) {
let xOnPic = event.clientX;
console.log(xOnPic);
setTimeout(onPic, 1000);
}
.testDiv {
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<div onmouseover="onPic(event)" src="./Pic/pic1.jpeg" class="testDiv">
</div>
You need to throw the event more often. Use onmousemove for that. If you want to restrict the amount of outputs you can do that with a variable.
var wait = false
function onPic(event) {
if (!wait) {
wait = true;
let xOnPic = event.clientX;
console.log(xOnPic);
setTimeout(() => wait = false, 1000);
}
}
.testDiv {
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<!DOCTYPE html>
<html>
<head>
<title>I have no title</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="test.css">
</head>
<body>
<div onmousemove="onPic(event)" src="./Pic/pic1.jpeg" class="testDiv">
</div>
<script src="test.js"></script>
</body>
</html>
I should note that this will only trigger if the mouse actually moved in between, but that is what you usually want.
If you always want to update simply set an variable and output that every second.
let interval = null;
let xPos = 0;
function onEnter() {
interval = setInterval(() => {
console.log(xPos);
}, 1000);
}
function onMove(event) {
xPos = event.clientX;
}
function onLeave() {
clearInterval(interval);
}
.testDiv {
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<!DOCTYPE html>
<html>
<head>
<title>I have no title</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="test.css">
</head>
<body>
<div onmouseenter="onEnter(event)" onmousemove="onMove(event)" onmouseleave="onLeave(event)" src="./Pic/pic1.jpeg" class="testDiv">
</div>
<script src="test.js"></script>
</body>
</html>
here is a working fiddle. Just use mouseenter mouseleave and mousemove and set Intervall.
JS fiddle
HTML
<svg id="svg" class="pic">
</svg>
JS
let mouseInPic = false;
let x;
$("#svg").on("mouseenter", () => {
mouseInPic = true
})
$("#svg").on("mouseleave", () => {
mouseInPic = false
})
$("#svg").on("mousemove", (e) => {
x = e.clientX
})
window.setInterval(function(){
if(mouseInPic == true){
console.log(x)
}
}, 1000);
Here you have a native JS implementation, with 1 second throttling of the updates, so it will console the position every second but not more often than every second. Since it is not possible to get the mouse position without a mouse event when mouse is over the element but not moving, you will need to remember the position of the mouse and store it into global variable, if mouse is moved on mousemove, just update the new position xOnPic.
Use mouseover and mousemove to detect if mouse is over the selected element and mouseout to detect when mouse is out of the element, so that you can stop printing to console.
var xOnPic = 0
var mouseOverPic = false;
var tryingToUpdate = false;
function tryToUpdate(){
if (!tryingToUpdate){
tryingToUpdate = true
console.log(xOnPic);
setTimeout(onPic, 1000);
}
}
function onPic(){
if (mouseOverPic){
console.log(xOnPic);
setTimeout(onPic, 1000);
}else{
tryingToUpdate = false;
}
}
document.getElementById('Pic').addEventListener('mousemove', function(e){
xOnPic = e.clientX;
mouseOverPic = true;
tryToUpdate();
});
document.getElementById('Pic').addEventListener('mouseover', function(e){
xOnPic = e.clientX;
mouseOverPic = true;
tryToUpdate();
});
document.getElementById('Pic').addEventListener('mouseout', function(e){
xOnPic = '';
mouseOverPic = false;
});
.testDiv{
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<!DOCTYPE html>
<html>
<head>
<title>I have no title</title>
<meta charset = "UTF-8">
<link rel = "stylesheet" href = "test.css">
</head>
<body>
<div id='Pic' src="./Pic/pic1.jpeg" class = "testDiv">
</div>
<script src = "test.js"></script>
</body>
</html>
Use
setInterval(onPic,1000);
I'm trying to implement a timer that will swap the larger image with the next image in line, I feel like I'm on the right track, but I'm not getting there. I can't use Jquery or (event.target), (event.srcElement) or appendChild. Any ideas? I don't think my function is doing anything right now. Current code below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Photo Gallery</title>
<script>
var aryImages[] = {"1.jpg", "2.jpg", "3.jpg"}
function changeImage(varImage) {
document.getElementById('bigImage').src='images/1.jpg';
for (var i = 1; i < 4; i ++)
index.html = "images/1.jpg" + photoOrder[i] +"sm.jpg";
}
</script>
/* styling elements */
<style>
img
{
width: 300px;
height: 290px;
padding: 2px;
}
body
{
text-align: center;
background-color: black;
}
</style>
</head>
<body>
<div>
<img src="images/1.jpg" id="bigImage" />
</div>
<img src='images/1.jpg' id='image1' onclick="changeImage(image1)" />
<img src='images/2.jpg' id='image2' onclick="changeImage(image2)"/>
<img src='images/3.jpg' id='image3' onclick="changeImage(image3)"/>
</body>
</html>
This should be what you're looking for. I set an interval that will rotate through your images. If the user clicks an image, that will change the image and reset the interval.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Photo Gallery</title>
<script>
var i = 1;
function changeImage(event, varImage) {
document.getElementById('bigImage').src='images/' + varImage + '.jpg';
// use this so the image interval doesnt
// interfere with user's click
if (event !== null) {
clearInterval(newInt);
newInt = setInterval(() => {
changeImage(null, i++);
if (i === 4) i = 1;
}, 500);
}
}
var newInt = setInterval(() => {
changeImage(null, i++);
if (i === 4) i = 1;
}, 500)
</script>
/* styling elements */
<style>
img
{
width: 300px;
height: 290px;
padding: 2px;
}
body
{
text-align: center;
background-color: black;
}
</style>
</head>
<body>
<div>
<img src="images/1.jpg" id="bigImage" />
</div>
<img src='images/1.jpg' id='1' onclick="changeImage(event, 1)" />
<img src='images/2.jpg' id='2' onclick="changeImage(event, 2)"/>
<img src='images/3.jpg' id='3' onclick="changeImage(event, 3)"/>
</body>
</html>
first of all you are not changing anything
you dont have a timer at all :)
here how to implement one:
setInterval(function(){
// do something;
}, 3000);
now inside the timer you should change images
for example
you should run inspect element on image to see changes because there is no images at these sources
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var currentImage = 0;
// assuming that image is the image index in the array.
var changeImage = function (image) {
document.getElementById('bigImage').src = 'images/' + images[image];
};
// now we can use setInterval function
setInterval(function(){
// check if we reached the last image
if(currentImage >= images.length -1) {
// if last image go back to first one
currentImage = 0;
} else {
// if not last image so give me the next
currentImage ++;
}
// do the image change
changeImage(currentImage);
}, 3000);
<img src="images/image1.jpg" id="bigImage" />
<button onclick="changeImage(0)" > image1 </button>
<button onclick="changeImage(1)" > image2 </button>
<button onclick="changeImage(2)" > image3 </button>
I am trying to achieve this function... I have a textarea with 600 maximum character limit (excluding numbers and symbols) and a counter (#chars). When the character limit has been exceeded, the send button (.send-message) will be disabled and character text counter (#chars) will turn red.
The problem is that i want the Excessive characters (above 600 alone) to turn red too on keyup.
$(document).ready(function(){
var char = 600; // Max character limit
$("#chars").html(char);
$("#editor").keyup(function () {
if ($("#editor").text().replace(/[^A-Z]/gi,"").length > char){
$('.send-message').removeClass('btn-default');
$('.send-message').addClass('disabled btn-danger');
}else if($("#editor").text().replace(/[^A-Z]/gi,"").length < 1){
$('.send-message').removeClass('disabled');
$('.send-message').addClass('btn-default');
}
else if(char <= 600){
$('.send-message').removeClass('disabled btn-danger');
$('.send-message').addClass('btn-default');
$('.send-message').attr('type', 'submit');
}
var rest = char - $(this).text().replace(/[^A-Z]/gi,"").length;
$("#chars").html(rest);
if (rest <= 100) {
$("#chars").css("color", "#f00");
}
else {
$("#chars").css("color", "#111111");
}
$("#excessChars") = $("editor").text().replace(/[^A-Z]/gi,"").length > char);
if (rest <= 0) {
$(rest).css("color", "#f00").text();
}
});
});
html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Accordion - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<style>
textarea {position: absolute; height: 100px; width: 300px; top: 100px; left: 30px;}
#test1 {background: rgba(0,0,0,0); color: red;}
#test2 {background: rgba(0,0,0,0); color: #000;}
</style>
<body>
<textarea id="test1"></textarea>
<textarea id="test2"></textarea>
<script>
$(document).ready(function(){
console.log('here');
$('#test2').on({
focus: function() {
console.log('here');
if (this.value.length >= 20) {
$('#test1').focus();
console.log(this.value.length);
}
},
keyup: function() {
if (this.value.length >= 20) $('#test1').focus();
$('#test1').val(this.value);
}
});
});
</script>
</body>
</html>
I am trying to add images on button click on canvas. . By default there is 1 image on canvas. Images are getting added on button click, But all images are erased when i click on canvas. Only the background image remains constant.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script src="fabric.js"></script>
</script>
<script>
function fun(){
var canvas = window.canvas = new fabric.Canvas('c');
fabric.Image.fromURL('compress/a.jpg', function(img){
canvas.add(img.scale(0.1).set({ left: 150, top: 200, angle: 20 }));
});
$(canvas.wrapperEl).on('mousewheel', function(e) {
var target = canvas.findTarget(e);
var delta = e.originalEvent.wheelDelta / 120;
if (target) {
target.scaleX += delta;
target.scaleY += delta;
// constrain
if (target.scaleX < 0.1) {
target.scaleX = 0.1;
target.scaleY = 0.1;
}
// constrain
if (target.scaleX > 10) {
target.scaleX = 10;
target.scaleY = 10;
}
target.setCoords();
canvas.renderAll();
return false;
}
});
}
function add()
{
window.canvas = new fabric.Canvas('c');
window.canvas.getObjects();
fabric.Image.fromURL('compress/b.jpg', function(img){
window.canvas.add(img.scale(0.1).set({ left: 150, top: 200, angle: 20 }));
window.canvas.selection = true;
window.canvas.renderAll();
window.canvas.calcOffset();
});
}
</script>
<style>
canvas {
border: 1px solid #999;
}
</style>
</head>
<body onload=fun()>
<div id="test" align="center" style="display: block">
<canvas id="c" width="600" height="600"></canvas>
</div>
<button id="but" onclick="add()">add images</button>
</body>
</html>
Please help me with this code
try using canvas.clear() before adding
This question already has answers here:
HTML5 Drag and Drop anywhere on the screen
(3 answers)
Closed 9 years ago.
I am trying to code up some JavaScript that will allow me to move a div on a web page. That is, I want to make it so that you can click and drag a div from one location on the page to another. My JavaScript doesn't seem to be cooperating. However, I feel like I am making a very simple error. Perhaps another pair of eyes can find my problem(s)?
Any comments are appreciated.
Below is my JS, CSS, and HTML:
JavaScript:
function getStyle(object, styleName) {
if (window.getComputedStyle) {
return document.defaultView.getComputedStyle(object, null).getPropertyValue(styleName);
} else if (object.currentStyle) {
return object.currentStyle[styleName];
}
}
function grabCalculator(e) {
var evt = e || window.event;
calculator = evt.target || evt.srcElement;
var mousex = evt.clientX;
var mousey = evt.clientY;
diffx = parseInt(calculator.style.left) + mousex;
diffy = parseInt(calculator.style.top) + mousey;
addEvent(document, "mousemove", moveCalculator, false);
addEvent(document, "mouseup", dropCalculator, false);
}
function moveCalculator(e) {
var evt = e || window.event;
var mousex = evt.clientX;
var mousey = evt.clientY;
calculator.style.left = mousex + diffx + "px";
calculator.style.top = mousey + diffy + "px";
}
function addEvent(obj, eventType, fnName, cap) {
alert("TEST");
if (obj.attachEvent) {
obj.attachEvent("on" + eventType, fnName);
} else {
obj.addEventListener(eventType, fnName, cap);
}
}
function removeEvent(obj, eventType, fnName, cap) {
if (obj.attachEvent) {
obj.detachEvent("off" + eventType, fnName);
} else {
obj.removeEventListener(eventType, fnName, cap);
}
}
function dropCalculator(e) {
removeEvent(document, "mousemove", moveCalculator, false);
removeEvent(document, "mouseup", dropCalculator, false);
}
function init() {
diffx = null;
diffy = null;
calculator = document.getElementById("calculator");
//store top and left values of calculator
calculator.style.top = getStyle(calculator, "top");
calculator.style.left = getStyle(calculator, "left");
calcButtonState = true;
}
window.onload = init;
CSS:
#calculator
{
position: absolute;
z-index: 1;
left: 37%;
top: 25%;
border: solid;
border-color: red;
background: black;
width: 25%;
height: 45%;
}
This is only the relevant CSS.
HTML:
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css">
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<div id="main">
<!--Calculator-->
<div id="calculator">
</div>
<!--End calculator-->
<header>
<div id="title">
Conversion Formulas
</div>
</header>
<nav>
</nav>
<div id="content">
<div id="dryMeasureContent">
</div>
<div id="wetMeasureContent">
</div>
<div id="distanceContent">
</div>
<div id="temperatureContent">
</div>
</div>
<footer>
</footer>
</div>
</body>
</html>
Note that my other HTML tags are in place, however, stackoverflow doesn't seem to handle HTML very well so they do not appear.
first of all, your init() function doesn't add any event listeners - this is the issue
try to add addEvent(calculator, 'mousedown', moveCalculator); after this line
calculator = document.getElementById("calculator");
i hope you understood my idea
Have you looked at the jquery library draggable http://jqueryui.com/draggable/ and droppable http://jqueryui.com/droppable/ ?
I've used these libraries with great success.
Super super easy to implement.
W3Schools has a great tutorial on drag and drop just using HTML5 and javascript.
<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev){
ev.preventDefault();
}
function drag(ev){
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev){
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">
</body>
</html>