2

Is it possible to use Javascript or JQuery inside CSS for a Chrome and Safari Browser?

If it is, can you give a simple example in each of these cases?

Prior answers referenced below have addressed how this might be accomplished with Internet Explorer or with Firefox with a focus on Javascript, but they have not addressed how to make these compatible for Chrome or Safari, which are very popular or possibly using JQuery as a workaround.

Thank you for you answers!

Prior answers provided by @Zach here include the following:

HTC with IE Use a CSS like:

 body {
  behavior:url(script.htc);
}

and within that script.htc file have something like:

<PUBLIC:COMPONENT TAGNAME="xss">
   <PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
   function main() 
   {
     alert("HTC script executed.");
   }
</SCRIPT>

The HTC file executes the main() function on the event ondocumentready (referring to the HTC document's readiness.)

XBL with Firefox Firefox supports a similar XML-script-executing hack, using XBL.

Use a CSS rule like so:

body {
  -moz-binding: url(script.xml#mycode);
}

and within your script.xml:

<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">

<binding id="mycode">
  <implementation>
    <constructor>
      alert("XBL script executed.");
    </constructor>
  </implementation>
</binding>

</bindings>
All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)

In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body, it will execute immediately on page load.

MMsmithH
  • 323
  • 1
  • 8
  • 1
    As `css` and `js` have virtually no functional overlap, there doesn't seem a standard way of invoking JavaScript calls inside CSS. Depending on what your needs are, CSS Houdini might offer some solutions (see https://css-houdini.rocks/js-in-css/ ). Otherwise, I'm curious why you'd specifically need JS inside CSS, when you can simply use JavaScript in the modern browsers you mentioned. – Bumhan Yu May 03 '22 at 05:10
  • In one case, I only have access to CSS file to modify a survey form in a purchased software, but would like to change around the functional behavior of the software. Since technically, workarounds exists for some browsers it was something I was thinking about doing. – MMsmithH May 04 '22 at 15:16
  • 1
    Ah I see. While I'm very interested in what potential solutions there are, my experience with such scenarios—i.e. a purchased software that doesn't allow any direct access to customized JS—has been that no custom JS behavior was achievable. I'd like to know if it's possible, and upvoting the question to help. – Bumhan Yu May 04 '22 at 16:52

0 Answers0