简体   繁体   中英

Add class to image in Squarespace using javascript or jquery

I thought this would be easy. I added this code injection into the header.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>$("img").addClass("example")</script>

The scripts appear in my page source, but have no effect adding a class to images. I've tried very specific div classes and ids, and other script variations, but again no effect.

Does Squarespace somehow prevent assigning classes? The image I'm trying to target currently has no class assigned to it. Squarespace gives every element a unique ID, but these can't be selected because they change every time the page is loaded.

You should do this:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(function() { $("img").addClass("example") }) </script> 
if you put your script in the head.

The $(function() {}) will wait till the document is loaded and call the function inside.

In Squarespace, when your custom Javascript doesn't seem to have any effect, or only works after a page refresh, it may have to do with Squarespace's AJAX loading :

Occasionally, Ajax may conflict with embedded custom code or anchor links. Ajax can also interfere with site analytics, logging hits on the first page only.

You may be able to disable AJAX for your template. Or, see the other approaches outlined here: https://stackoverflow.com/a/42604055/5338581

Note that this only applies to certain templates. Without stating the template you are using nor including a link to the site/page in question, one can only guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM