Simple javascript
-
I’d like to include one simple javascript function in about a third of the posts on my site. I’ve studied how to do this for several hours, tested several plugins, edited various files in my theme, etc., but I just can’t seem to make it work, and would appreciate advice.
The function just tests for the date and either inserts a link in a reference to a post, or doesn’t. (So that there’s only a link after the post is live, and the link is functional.)
Here’s my function:
$(function() {
var ds = $(“.dateswitch”),
now = new Date();
if (Date.parse(ds.data(“switchdate”)) < now) {
ds.find(“.beforeswitch”).hide();
ds.find(“.afterswitch”).show();
}
});And here’s html that uses it:
<p class=”dateswitch” data-switchdate=”2017-07-04″>
The post
<span class=”beforeswitch”>“Test Post” will be</span>
<span class=”afterswitch” style=”display:none;”>“Test Post” was</span>
published on Friday, 4 August 2017.
</p>I’m mildly competent with basic WP issues, but completely new to javascript. (I got this script from someone else.) I’ve tried including my function in a javascript file in my theme, and calling that; including it in the footer; including it just in the post; including it in several plugins; etc., but it just doesn’t work. (It works just fine as a js fiddle, so I’m confident of the function itself.)
My question:
How exactly should I include this function in my posts?- If as a js file, where should I put it, and how should I call it? For example, should I call it with a fixed address (a normal web url) or use get_theme_root_uri?
- If in the footer, do I just put this function inside a script tage? If so, what exactly should it look like?
- Does the function need a name of some kind? So far, I’ve just put the exact function above in the js file, and used the exact html above. Do I need to include some reference to the specific function? How?
If there’s an easier way, I’m happy to use it. I looked at advice on enqueueing, but I think it’s beyond me. I’ve tried the plugins Scripts n Styles and Simple Custom CSS and JS, but the function still didn’t work. My guess is that I’m making a reference mistake somewhere, but I’m not sure where. My theme is called Nirvana-child-testing, if that helps in specifying references and locations.
- The topic ‘Simple javascript’ is closed to new replies.