I want to print out a picture whenever the mouse is clicked on the screen. This is my current Javascript and HTML code. It only prints the h1, I don't know what I am doing wrong.
var image = document.getElementById("im"); // idenfitifes span eleme nt
var roll = false; // to know the image is moving or not , intitally it is not moving state hence value is false
image.addEventListener("mousedown", start, false); // at starting image is in rest
function mouse_move(x) // funciton to move image with mouse
{
var newX = x.clientX; // copies mouse x position
var newY = x.clientY; // copies mouse y position
image.style.left = newY + "px"; // assigns latest mouse position to span (image)
image.style.top = newX + "px";
}
function start(x) // span (image) starting no rolling mode
{
if(roll){ // when the mouse is moving
document.removeEventListener("mousemove", mouse_move); // initiages image span move
roll = !roll;
return;
}
roll = !roll; // when the mouse is not moving
document.addEventListener("mousemove", mouse_move, false);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Picture of Me! </title>
</head>
<body>
<h1> HTML File to move image along with mouse movement. </h1>
<script type="text/javascript" src="h5j.js">
<span id="im">
<img src="https://static01.nyt.com/images/2020/04/27/us/politics/00-trump-cand-page/00-trump-cand-page-mediumSquareAt3X.jpg" height="120" width="120"></img>
</span>
</body>
</html>
You Use The AddEventListener Function Like This
the syntax for addEventListener is: addEventListener("Event Name", "Your Function name, the function you want to run after event happening")
when you need to run in the click event, you simply need to change Event name from "mousedown" to "click" , example: document.addEventListener("click", mouse_move, false);
you have to use "click" event instead of "mousedown" like:
document.addEventListener("click", mouse_move, false);