Was trying to make a minesweeper in javascript and ran into this problem...
I created a table and each td is a "box" with either a mine or nothing(Currently) in it. After I click on a box, the javascript should change the onclick from "clicked(this.id)" to an alert that says "NOPE"(made an alert just to test if something was happening), but what happends is:
For some reason, the onclick returns to its original value (clicked(this.id))..
I made a test page, a table with 2 td's and the same thought in mind(change onclick value after it's clicked) and it works.. I have no idea how to fix this...
The test.html that does work: http://pastebin.com/62ayRJps
The HTML from the site that doesn't work as intended: http://pastebin.com/SZ6NU8j9
And the Javascript from the site that doesn't work as intended: http://pastebin.com/bevJHNLc
The "Cannot read property 'click' of undefined" error occurs when trying to call the click() method on an undefined value. To solve the error, run the JS script after the DOM elements are available and make sure you only call the method on valid DOM elements.
using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute. In other words, adding return false stops the href from working. In your example, this is exactly what you want.
We can use bind() unbind() / on() off() as below to avoid multiple click. We can use one() function to happen click only once.
It's a new paradigm called "Unobtrusive JavaScript". The current "web standard" says to separate functionality and presentation. It's not really a "bad practice", it's just that most new standards want you to use event listeners instead of in-lining JavaScript.
Your click event handlers are being reset because of this line in clicked(id)
:
document.getElementById("minesweeper").innerHTML += ammountClicked+" - "
Each table cell has a onclick='clicked(this.id);'
attribute in its HTML. When you assign your test function tst
to the table cell DOM object, you're setting the onclick
property of the DOM object, but that doesn't change the onclick
attribute of the HTML. (Yes, it's confusing.)
In the line of code above, the browser reads the innerHTML
from the minesweeper div
(which has the original onclick
attributes), concatenates it with another string, then reassigns the result back to the minesweeper div
. This wipes out the original contents of the div
and replaces it with the new HTML (a table where every cell has the original onclick
attribute).
If you want to have a message area, I suggest setting innerHTML
on another element: Demo
In the demo, I changed line 49 (adding a span
):
print += "</table><span id='message'></span>";
and line 107 (assigning the text to the span
):
document.getElementById("message").innerHTML += ammountClicked+" - ";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With