Search code examples
javascripthtmlmathml

add onclick action to mathml


I'm trying to add some actions to be executed when the arrows in following page are clicked:

<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1">


	<script type="text/javascript">

		function createActions() {
			var div = document.getElementById("l");
			div.onclick=function(){alert("HI")};
		}

		
		window.onload = createActions;
	</script>
</head>
<body>

	<math>
		<mn>12</mn>
		<mo>&#x00D7;<!-- × --></mo>
		<mi>a</mi>
		<munderover>
			<mo>=</mo>
			<mo id="l" style="color: red;">&rarr;</mo>
			<mo style="color: red;">&larr;</mo>
		</munderover>
		<mi>24</mi>
	</math>
			
</body>
</html>

Debugger shows that element "l" is returned by the call to "getElementById", but the definition of the "onclick" attribute does nothing.

In addition to previous test, I've also tested without javascript and with the mathml:

<mo onclick='alert("HI")'>&rarr;</mo>

also without success.


Solution

  • Use addEventListener() Method

    count = 1;
    document.getElementById("l").addEventListener("click", function(){
        alert("You clicked "+ count++ +" times");
    });
    <html>
    <head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    </head>
    <body>
    
    	<math>
    		<mn>12</mn>
    		<mo>&#x00D7;<!-- × --></mo>
    		<mi>a</mi>
    		<munderover>
    			<mo>=</mo>
    			<mo id="l" style="color: red;">&rarr;</mo>
    			<mo style="color: red;">&larr;</mo>
    		</munderover>
    		<mi>24</mi>
    	</math>
    			
    </body>
    </html>