Js and wordpress help...where does it go? - javascript

So ive been putting off using js for a while because everytime I try to figure it out I get more confused, but now I really need it for a site im working on...
I want to hide the page until everything loads (so you don't see elements moving/jumping into place.
I've found various bits on here and around the web, but everytime I go to place the code anywhere that I feel it should go, I get errors.
take this for example:
window.onload=function() {
document.getElementById('loading-mask').style.display='none';
}
Ive tried going to the functions.php file and adding the js code i've found on the web but always get an error. So where do I copy the code for this, so it affects the CSS ive added?

In wordpress, you need to use a plugin to help you insert your javascript/jquery
Login to wordpress
Go to plugins>>add new
Search for Insert Headers and Footers plugin
Install and activate
Then launch the plugin and insert your javascript.
You will need to select the location of your javascript, either in the tag or just before the closing

When you add javascript to a wordpress website, you want to do it in one of two ways. You can either do it using a hook which is essentially a 'spot' in the code you wish to add to.
This can be done by placing the following in your functions.php
add_action('wp_head', 'wp_54885300_add_js_to_header');
function wp_54885300_add_js_to_header(){ ?>
<script>
window.onload=function() {
document.getElementById('loading-mask').style.display='none';
}
</script>
<?php
}
Alternatively, if you find yourself needing to place lots of javascript into your website, you may wish to link to an external javascript file. This can be done with wp_enqueue_script().
Place the following in your functions.php file to enqueue an external stylesheet to your website.
add_action( 'wp_enqueue_scripts', 'wp_54885300_enqueue_script' );
function wp_54885300_enqueue_script(){
wp_enqueue_script('anyname', 'path-to-file.js', array(''), 'version', false );
}
As others have pointed out, what you are trying to do by hiding everything until the window has completely loaded may not be a good idea for a number or reasons.
But, atleast to the best of my knowledge, this ^^ is the proper way to include JS into a wordpress installation without depending on a plugin to get you started.

Related

Why is my JavaScript/jquery code in my Functions.php file only working on the first loaded post on my WordPress site?

I am working on a WordPress site where the content will be replaced each week (any posts, media or files are wiped from the WP environment each week, and then repopulated with all new content, and so on).
One of the main features of the post pages, is that I will have to copy and paste local URLs from a Word document directly into the WordPress post. Since the original hyperlinks lead to a file saved on my local system, the hyperlinks obviously do not link properly on the WordPress site. I have created a small script for this using REGEX concepts to automatically change hyperlinks depending on the category.
This code snip-it is saved in my functions.php file (loads locally saved script that does the actual link change magic):
Function load_js_assets_Tab2 () {
if( in_category('10')) {
wp_enqueue_script('tab2LinkReplace','https://myserver/wordpress/wp-content/tab2LinkReplace.js', array('jquery'), '', true);
}
}
add_action('wp_enqueue_scripts', 'load_js_assets_Tab2');
THE PROBLEM:
For some reason, this script only works on the first post I load, then does not apply to all the following auto loaded posts. No matter which post I click first, the script works, but will not for any following posts as I scroll down through the posts. The 'auto load next post' feature is built right into my template Newsblock (https://newsblocktheme.com/).
I am assuming this has something to do with the fact that the auto load next post feature is done via AJAX loading, but I have no idea how to fix this.
If any one has any suggestions, work arounds or ideas on how to approach this differently... I would really appreciate it!
The Ajax is probably the issue and the hyperlinks fixing thing isn't being recalled.
You can used $(document).bind('ajaxComplete') to do things after every Ajax request and you can use this as a trigger the rerun that function
You'd just include this inside you tab2LinkReplace.js file, but I'm not sure how that JS works so I just left some basic comments
$(document).ready(function() {
$(document).bind('ajaxComplete', function(){
// was new post loaded?
// new post has loaded
// call function
// or manually fix:
// - loop through each newly created link:
// - > Fix Link w Magical Regex
});
});

Loading div from html file using jQuery under Gutenberg

I know many many similar questions have been asked, and I've scoured them to see if I could find a solution to this very simple problem. As you might guess, I'm an extreme beginner to js, so please forgive me if this is a very silly question.
On my wordpress index page, I'm trying to load an iframe within a div from a separate html file (that also lives on my server). I'm essentially doing so to make sure that an embedded spotify playlist is not the first thing indexed by google when it crawls my site (right now, it has decided that the list of songs on that playlist is a more appropriate description for my site than the meta description orany other text on the site.) I'm hoping that by loading the iframe from an external html using window.load, it will only be crawled at the end of the process, and will thus be reprioritized by google (with the added benefit that any slow loading times from spotify will only occur after the rest of the page has loaded).
Using methods I found here on stackoverflow I created an html file that has nothing but the iframe code generated by spotify:
<iframe src="https://open.spotify.com/embed/playlist/2JVOQhDOZlNSRGw73rl3J9?theme=0" width="100%" height="260" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>
Then, in the head of my wordpress index, I've included the following javascript:
<script>
jQuery(window).load(function () {
$('#spembed').load("http://www.palmsout.net/spotifyindex.html")}
});
});
</script>
Finally, I've created an empty div on my front page with the id "spembed"
<div id="spembed"></div>
I was hoping this method would replace the empty content in the div with the iframe in spotifyindex.html -- but it doesn't seem to be working. the div still renders blank, and I'm not seeing any console errors that refer to the code I'm using (though again, I'm a true beginner so I may be misunderstand what I'm seeing in the console). I'm sure I'm missing something really elementary here, but I cannot figure out what it is.
If someone would help me, I'd appreciate it. And if anyone has any ideas about how this might help me with my google search problem (or better solutions, etc.), I'm all ears.
Thanks!
ps. I've enqueued jquery already, using the following code, but I can't seem to get a straight answer about whether I actually need to do this.
function theme_scripts() {
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'theme_scripts');
You will need to register jQuery as a dependency if you are using it in a script. However, in most cases I believe it was already included by something else.
Second, I'd put that code in a separate js file an load it like this:
add_action( 'wp_enqueue_scripts' , function () {
wp_enqueue_script( 'spotify_embed' , 'path/to/spotifiy-embed.js' , array( 'jquery' ) );
} );
In the jQuery-part try
jQuery( document ).ready( function () {
jQuery( '#spembed' ).load( 'http://www.palmsout.net/spotifyindex.html' );
} );

Wordpress and Javascript, whats wrong?

i am making my own custom wordpress theme. And I am having a problem with javascript. I have writing code in the functions.php. All css is working, but I cant manage to make a toggle menu (for responsive purpoises). Maybe I am doing something wrong ? I copy my code from function.php at the bottom. P.s. i also created javascript.js for the code. But i can't figure whats the problem.
function pirma_enqueue_styles(){
wp_enqueue_style('custom_s_s',trailingslashit(get_template_directory_uri()) . 'css/style.css'); wp_enqueue_style('javascript',trailingslashit(get_template_directory_uri()) . 'js/js.js');
}
add_action('wp_enqueue_scripts', 'pirma_enqueue_styles');
If you created the resource file javascript.js, you simply enqueued the wrong script (namely js/js.js). Also look out for the correct path: You declared that the file is in the directory js.
Also - and more important in this case - to include scripts you need to use wp_enqueue_script(), not wp_enqueue_style().

Need Help in Integrating Javascript with Wordpress

I have wordpress account for blogging. Recently I have opted for PopUpAds. I have the javascript code with me which I received from PopUpAds.
Can any one please tell me how to integrate this code into wordpress??
Any informative links will also be very helpful.
Thank You In advance.
It might be the safest ( but not the best ) way to install the plugin which allows you to add inline javascript code.
I.e. something like this - https://wordpress.org/plugins/tc-custom-javascript/
Also, if you can edit functions.php file within your active theme, the quickest way is to add a patch of code there:
<?php //add opening php tag only if there is closing tag at the end of functions.php file
function pop_up_ads_script() {
?>
<script type="text/javascript">
//your script from PopUpAds goes here
//check if PopUpAds code includes also script tags, then avoid adding duplicate tags
</script>
<?php
}
add_action( 'wp_footer', 'pop_up_ads_script' );
For this approach, be careful when editing and saving functions.php, since you might cause error due to bad syntax or typo, so first check if php tags. I
would suggest to do this via FTP access, rather than through built-in WordPress file editor.
Using a Wordpress plugin that lets you insert arbitrary HTML code as a shortcode is the best way to go IMO. That way the external code doesn't mess with the wysiwyg editor. I use this plugin: https://en-ca.wordpress.org/plugins/insert-html-snippet/
If the JavaScript code should be added to the head section of your page, there are plugins that do that as well.
Check out this useful blog post for adding external JS and CSS to Wordpress: http://blog.dynamicdrive.com/add-custom-javascript-css-wordpress/

JavaScript in a WordPress post

How can I add
<a href="javascript:function foo(){alert('hi');}" title="alert">
Drag to your bookmarks bar
</a>
to my WordPress post?
I built a bookmarklet and I want to pass it through my blog, but WordPress is stripping out the javascript from my post when I save it.
Javascript in WordPress Single Pages and Posts
<script type="text/javascript">
<!--
// your code
//--></script>
Source:
https://codex.wordpress.org/Using_Javascript
I have no issues embedding that code in the HTML editor on my wordpress site. There is a problem with your javascript code- that defines a function, but never calls it. I have
Drag to your bookmarks bar
in a post, and I get the alert when click, as well as the bookmarklet.
The issue is likely to be caused at the browser end. Chrome's XSS was the problem for me and I solved it by adding the line header ("X-XSS-Protection: 0"); to wp-blog-header.php in the root folder of my installation. This may not be ideal as it applies across the whole site. It would probably be better to add it where it would only apply to the post/page which needs to render the bookmarklet.
This is old, but still relevant with Version 4.9.5 for wordpress, so I answer with my solution for this:
Wordpress filters out any Javascript you use in your Posts or pages, that is why your code gets lost. I did the following steps to add a "javascript:" Link:
Add the Link you want to your post, use "#" as the href and add a id to the tag (in Text-Mode of the Editor):
This is my JS Link
Install a Custom Javascript Plugin. I used Simple Custom CSS and JS
Add the Javascript you want with help from the plugin:
jQuery(document).ready(function( $ ){
function yourFunction() {
alert("It works");
}
jQuery('#idOfYourLink').on("click", yourFunction);
});
The important part is adding the on-Handler to the Link you want to use. Now the Javascript is loaded right after the page got loaded. And a click on the link will call the function yourFunction
I guess that wordpress editor is used to work with textual data/content. So, to add your js you can find plugin for adding custom js. Also you can add a Custom field to the posts.
Let it be "custom_js" - the name of a field that would contain js code. And then edit theme post temlate, adding "echo" of custom_js.
<?php
//single.php
echo get_post_meta( get_the_ID(), 'custom_js');
?>

Categories

Resources