Third level of quote escaping in HTML and JavaScript
Asked Answered
M

2

10

I'm going to preface this with: "I know this is bad practice and an ugly hack (and I'm sorry) but..."

I'm using jQuery TOOL's tooltip widget to display a tooltip on an html element when the user hovers over it. With this widget you add the tooltip's html to the element's title attribute.

Inside of that html I have an element onto which I want to bind an inline onclick event handler.

Unfortunately I've run into too many layers of quotes to pass a parameter to the function I'm trying to call.

I have something like this:

<div title="<div onclick='myFunction(_____)'>My tooltip content</div>">My element</div>

This works if I need to pass an integer to myFunction since it doesn't need another set of quotes. Unfortunately I want to pass a string to myFunction. How can I further escape this string parameter so that it doesn't close the onclick or the title string?

Monegasque answered 2/4, 2013 at 22:22 Comment(2)
Check out a similar question here: https://mcmap.net/q/109483/-escape-quotes-in-javascriptTulatulip
Thanks @wilsjd, that indeed is a working solution.Monegasque
S
9

Inside of HTML attributes, you should encode quotes as HTML entities, e.g.:

<div title="This says &quot;Hello!&quot;">
    Hello!
</div>
Silicle answered 2/4, 2013 at 22:26 Comment(2)
This worked. Can you explain if this is a part of HTML that allows &quots to be run as regular quotes in a JavaScript function or if this is some magic being done by jQuery TOOLs or if it's something else?Monegasque
It's unrelated to JavaScript. This is just the way you would escape a double quote within a double-quoted HTML attribute. It's comparable to something like alert("This says \"Hello\"") in JavaScript.Silicle
M
0

I was able to find a solution to my particular problem. Not sure if this works in the general case or if jQuery TOOLs is doing something magical to unescape my string but I ended up escaping with &quot; and it did evaluate into valid Javascript that was executed.

Something like this:

<div title="<div onclick='myFunction(&quot;_____&quot;)'>My tooltip content</div>">My element</div>

I don't really understand how this is working to be honest. Would love if someone could clarify what part of the process is changing those &quot;s into actual functional quotes.

Monegasque answered 2/4, 2013 at 22:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.