issue getting mouse coordinate - javascript

I use below code to capture mouse coordinate, and bind it to a div(container). and there's one more div called subDiv inside container. I found that no matter where I move inside subDiv, the coordinate is always the one I just entered subDiv (e.g. I enter subDiv at (10,10), no mater where I move in subDiv, the coordinate is always (10,10)).
Anybody know why?
var x,y;
var e = e||window.event;
return {
x:e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,
y:e.clientY+document.body.scrollTop+document.documentElement.scrollTop
};

What you pasted works as following demos. Check other code.
<!DOCTYPE html>
<html>
<head>
<script>
function test(e){
var x,y;
var e = e||window.event;
return {
x:e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,
y:e.clientY+document.body.scrollTop+document.documentElement.scrollTop
};
}
function myFunction(event){
var x = test(event);
document.getElementById("demo").innerHTML=x.x + '.' + x.y;
}
</script>
</head>
<body>
<div id="container">
<div id="subDiv" style="width:199px;height:99px;border:1px solid" onmousemove="myFunction(event)"></div>
</div>
<p id="demo"></p>
</body>
</html>

Related

How to make a button in HTML which decrement a variable?

I am trying to decrement the variable Stock by 1 each time I click the button but it's not working. The value on the website stays the same no matter how many times I click the button:
var Stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = Stock;
}
function ButtonFunction() {
Stock--;
}
<body onload="myFunction">
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>
Your function only changes the value of the Stock variable.
It doesn't change the value of document.getElementById("myText").innerHTML which only gets changed when you call myFunction (something you never do).
You need to:
Actually call myFunction when the document loads
Call it again whenever you change the variable.
let stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = stock;
}
function buttonFunction() {
stock--;
myFunction();
}
document.querySelector("button").addEventListener("click", buttonFunction);
addEventListener("load", myFunction);
<button>ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
Also note that by convention, variable names which start with a capital letter are reserved for classes and constructor functions in JS, so rename your variables.
It looks like the variable is being decremented, but the inner text of the span is not then updated.
Try calling myfunction() after each click ;)
There's a number of things going on here. The one I think you're primarily interested in has been answered by Quentin. Others however remain and are (I think) far better habits to get into than variable naming conventions.
Inline event handlers = bad. Events that can be removed or supplemented = good. Use attachEventListener for the most control.
Functions with names that offer nothing are a pain. Names are the most helpful when they're descriptive.
Functions that change and display a variable can be traps. It's often better to have a third function which calls both a function to change something and another function to display it.
Here's yet another approach:
window.addEventListener('load', onLoaded, false);
function onLoaded(evt) {
displayStock();
document.querySelector('button').addEventListener('click', onButtonPressed, false);
}
var unitsOfStock = 10;
function displayStock() {
document.getElementById('myText').textContent = unitsOfStock;
if (unitsOfStock == 1)
document.getElementById('plural').textContent = '';
else
document.getElementById('plural').textContent = 's';
}
function decreaseStock() {
unitsOfStock--;
}
function onButtonPressed() {
decreaseStock();
displayStock();
}
<button>ClickMe</button>
<h1>The value for Stock is: <span id="myText"></span> unit<span id='plural'></span></h1>
var Stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = Stock;
}
function ButtonFunction() {
Stock--;
myFunction();
}
<body onload="myFunction()">
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>
I hope it helps you. You have to call myFunction to show the new value of Stock variable in myText id in your click handler ButtonFunction().
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var Stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = Stock;
}
function ButtonFunction() {
Stock--;
myFunction();
}
</script>
</head>
<body onload="myFunction" >
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>
</html>
Whenever you click the 'Click me' button, ButtonFunction() will be called. and document.getElementById("myText") get find the html element with the id myText and reference itself to the html element. innerHTML will allow you to place your html code inside it and innerText allows you to put your text the html element with an id of myText.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var Stock = 10;
function ButtonFunction() {
Stock--;
document.getElementById("myText").innerHTML = Stock;
}
</script>
</head>
<body>
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>
</html>

"onend" in ResponsiveVoice does not mean AFTER playing text?

I need to play some text and ONLY THEN perform the following actions (e.g. hiding the "pause" and "stop" buttons), but they are hidden IMMEDIATELY when I start playing the text. Simplified situation - see code.
Many thanks for the advice..
<!DOCTYPE html>
<html>
<body>
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<script>
function Voice(id){
var element = document.getElementById(id);
var text = element.innerText;
responsiveVoice.speak(text, "UK English Male", {onend: Hide("div1")});
}
function Hide(id){
var element = document.getElementById(id);
element.style="visibility: hidden";
}
</script>
<div id="div1">This is the first line.</div>
<div id="div2" onclick = 'Voice("div2")'>
This is the second line.
</div>
<br>
Click on the second line to play its text. The first line should be hidden after the message is played.<br>
But it is hidden IMMEDIATELY after clicking. What is wrong?
</body>
</html>
The solution is to use arrow: {onend: () => Hide()} instead of {onend: Hide()} (Thanks to CertainPerformance).
onstart:, onend: and rate: can even be used simultaneously. There is only one small problem - after changing the content of the page, there is a long delay when using the ResponsiveVoice function for the first time. See code:
<!DOCTYPE html>
<html>
<body>
<script src='https://code.responsivevoice.org/responsivevoice.js'>
</script>
<script>
function Read(id){
var element = document.getElementById(id);
var text = element.innerText;
responsiveVoice.speak(text, "UK English Male", {rate: 1.3, onstart: () => Show(), onend: () => Hide()});
}
function Show(){
var element = document.getElementById("Pause");
element.style="visibility: visible";
}
function Hide(){
var element = document.getElementById("Pause");
element.style="visibility: hidden";
}
</script>
<div id="div" onclick = 'Read("div")'>This is text to read.</div>
<br>
<input type = "button"
id = "Pause"
value = "Pause"
style = "visibility: hidden" />
</body>
</html>
You need to pass a function that calls Hide, rather than calling Hide immediately:
{onend: Hide("div1")}
calls hide as soon as that line is evaluated. It needs to be:
{onend: () => Hide("div1")}
<!DOCTYPE html>
<html>
<body>
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<script>
function Voice(id){
var element = document.getElementById(id);
var text = element.innerText;
responsiveVoice.speak(text, "UK English Male", {onend: () => Hide("div1")});
}
function Hide(id){
var element = document.getElementById(id);
element.style="visibility: hidden";
}
</script>
<div id="div1">This is the first line.</div>
<div id="div2" onclick = 'Voice("div2")'>
This is the second line.
</div>
<br>
Click on the second line to play its text. The first line should be hidden after the message is played.<br>
But it is hidden IMMEDIATELY after clicking. What is wrong?
</body>
</html>

Weird error for use of keyCode should be working

I'm getting an error with my event.keyCode saying that
Cannot read property 'keyCode'
I want the code to when I press "I" to load the screen that I have drawn onto my canvas
var canvas = document.querySelector("canvas");
document.addEventListener('keydown', loadScreen);
canvas.width=640;
canvas.height=640;
var draw = canvas.getContext("2d");
loadScreen();
function loadScreen(event) {
var key = (event.keyCode);
if(key == 73)
{
InventoryScreen();
}
}
function InventoryScreen()
{
draw.fillStyle = "#D3D3D3";
draw.fillRect(50,50,100,80);
draw.fillRect(50,135,100,80);
draw.fillRect(50,220,100,80);
draw.fillRect(50,305,100,80);
draw.fillRect(50,390,100,80);
draw.fillRect(50,475,100,80);
draw.fillRect(495,50,100,80);
draw.fillRect(495,135,100,80);
draw.fillRect(495,220,100,80);
draw.fillRect(495,305,100,80);
draw.fillRect(495,390,100,80);
draw.fillRect(495,475,100,80);
draw.fillRect(155,50,335,505);
}
I think your issue is here:
loadScreen();
You are calling loadScreen without passing it an event.
You can fake it by doing this:
loadScreen({keyCode:73});
Note that when loadScreen is set to be called by an Event here:
document.addEventListener('keydown', loadScreen);
…every time a keyboard key is pressed down, an event object is passed as the first argument, and that event object contains a keyCode value that corresponds with the key pressed.
I was able to wrap your code in a test HTML document, and it produced some nice-looking gray rectangles:
<!DOCTYPE html>
<html>
<head>
<title>Test of Stackoverflow question 49583733</title>
<script type="text/javascript">
window.addEventListener('load', () => {
your code here, adding {keyCode:73}
}) ;
</script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>

onmouseout event not working with h1 tags

I am trying onmouseout and onmouseover events. Below code is working fine if i remove tags, what is confusing me is , with tags, only mouseover is firing and not mouseout. Please guide what i am doing wrong.
<!DOCTYPE html>
<html>
<body>
<div onmouseout="mouseout();" onmouseover="mouseover();" id="test"><h1> Mouse </h1> </div>
<div id="count"> </div>
<div id="count2"> </div>
<script>
var textonout = "<h1>Mouse out</h1>";
var count =0;
var out = 0;
var textonover = "<h1>Mouse Over</h1>";
function mouseout() {
document.getElementById("test").innerHTML = textonout;
document.getElementById("count2").innerHTML = out++;
}
function mouseover() {
document.getElementById("test").innerHTML = textonover;
document.getElementById("count").innerHTML = count++;
}
</script>
</body>
</html>
EDIT: Ok i think i understand my own question. In my case, onmouseout event doesnt fire if i have nested tags. I have tried the same code just replacing h1 tag with a div tag. I tried several combination (using span etc) as soon as i introduce any tag inside my first div, onmouseout stops working.
Can someebody guide me what is the issue ? i am not asking for the fix, i just want to understand the reason of this error.
EDIT(2). Another update, if i add the following lines, now the onmouseout event is triggering.
function mouseover() {
document.getElementById("test").innerHTML = textonover **+ count**;
document.getElementById("count").innerHTML = count++;
DEMO
Uncaught ReferenceError: mouseout is not defined
You had this error in your console. I admit, I prefer to seperate js and html. Call your events in your JS.
Additionally, you don't need to recreate an h1 everytime you want to change the text. Just add an id to your h1, and replace the text inside of it.
HTML:
<div id="test">
<h1 id="h1"> Mouse </h1>
</div>
<div id="count"></div>
<div id="count2"></div>
Javascript:
var h1 = document.getElementById('h1');
textonout = "Mouse out";
var count = 0;
var out = 0;
var textonover = "Mouse Over";
var test = document.getElementById("test");
test.onmouseout = mouseout;
test.onmouseover = mouseover;
function mouseout() {
h1.innerHTML = textonout;
document.getElementById("count2").innerHTML = out++;
}
function mouseover() {
h1.innerHTML = textonover;
document.getElementById("count").innerHTML = count++;
}
Follow this , it work perfect.
<!DOCTYPE html>
<html>
<body>
<h1 id="test"> Mouse </h1>
<div id="count"> </div>
<div id="count2"> </div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
var textonout = "Mouse out";
var count =0;
var out = 0;
var textonover = "Mouse Over";
$("h1").mouseover(function(){
$("h1").css("background-color","yellow");
document.getElementById("count").innerHTML = count++;
document.getElementById("test").innerHTML = textonover;
});
$("h1").mouseout(function(){
$("h1").css("background-color","lightgray");
document.getElementById("test").innerHTML = textonout;
document.getElementById("count2").innerHTML = out++;
});
});
</script>
</body>
</html>

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Categories

Resources