Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape quotes inside an inline javascript function

My function is running perfectly without using class in appended div but when I try to add a class on the element it is not working.

<head>
    <script type="text/javascript">
        function showt(id){
            $('body').append(id)
        }
    </script>
</head>

<body>
    <a href="#" id="hidemain" onmouseover='showt("<div class='sdf'>appended</div>")'>show detail</a>
</body>
like image 542
jchand Avatar asked Sep 16 '26 02:09

jchand


1 Answers

Just escape quotes, when used inside other quotes. Also just use the respective other quotes inside the attribute. So if you enclose the attribute in " just use ' and \' inside and vica verse. (Thanks to @nnnnnn for mentioning this!)

<a href="#" id="hidemain" onmouseover="showt('<div class=\'sdf\'>appended</div>')">show detail</a>

or

<a href="#" id="hidemain" onmouseover='showt("<div class=\"sdf\">appended</div>')">show detail</a>

EDIT

In order to get the event object, you should add the event handler programatically like this:

<a href="#" id="hidemain">show detail</a>
<script>
  document.getElementById( 'hidemain' ).addEventListener( 'click', function( event ) {
    showt( '<div class="sdf">appended</div>' );
    // here you have access to event and thus event.pageX
  });
</script>
like image 156
Sirko Avatar answered Sep 18 '26 16:09

Sirko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!