HTML snippet as parameter of a javascript function

Asked

Viewed 197 times

0

I have little knowledge of javascript, how can I pass a code embedding some video in a function as a string?

<a href="javascript:void(0)" onclick="exibirVideo('CODIGO DE EMBED AQUI')">

I’m having problems because I can not pass the embed of the video as string, which ends the tag <a> prematurely with some of the > embed interns

1 answer

1

If you set the "click" anchor callback on <script*src=*>*</script> you will never have to face script-inline problems.

Your problem should be related to quotation marks, it is possible to resolve using quotation marks (") whether an apostrophe was used in the anchor attribute (') to represent a value, or vice versa.

If you want to represent a quote or apostrophe in a string in Javascript you can escape it with , for example: <a onclick='"\' apóstrofo - \" aspa"'></a>. Or:

"\x22" // aspa (ASCII)
String.fromCharCode(0x22) // aspa
String.fromCharCode(34) // aspa
"\x27" // apóstrofo (ASCII)
"\u0022" // aspa (UTF-8)
"\u0027" // apóstrofo (UTF-8)

Key example of tag usage <script/>.

<script>
document.querySelector('a').onclick = function() {
    exibirVideo('\
                Embed code')
}
</script>
  • 1

    Hello @nicematt, Thanks for the reply, is that on the same page I will have several embeds that would only be loaded (I actually use php to acquire these embeds from a database and make a manipulation to also pass in the video display the id of the div where I will use Document.innerHTML), I solved this problem by creating a <input type="Hidden" value="embed_code"> with an id and the value of that input would be the embed php string using htmlentities() php function

  • I’m going to leave here an embed of a video that I took in the Vimeo for testing: <iframe src="https://player.vimeo.com/video/176377950?title=0&amp;byline=0&amp;Portrait=0" width="640" height="360" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>

  • without problems, I believe that the problem that I was having before was given by the ">" in the end, ended up closing the chor prematurely

  • Wait, you’re putting an HTML code inside an attribute, is that it? It is possible to escape characters in this code, but if your solution worked, it is okay, but the problem is in the quotes. I would still recommend using the "script" tag to make the project more organized

  • 1

    unfortunately as the case is very specific, I believe it looks better the way I did for this case, but for others the tip was very useful! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.