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' );
} );
Related
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.
I used this method before.
<iframe data-src="https://youtube.com/...?autoplay=1"></iframe>
On event with javascript I turned the data-src to src and the video started to play.
I had browser caching problems with that, videos autoplaying in background (I load a thumbnail in place for the actual iframe) when going back in the browser. Because of that I switched to a method where I just load the iframe inside a comment
<!--<iframe src="https://youtube.com/...?autoplay=1"></iframe>-->
and then remove the comment on click. I saw Google using this exact method on Google plus. Problem is caching again now, this time server side. I think very likely cloudflairs auto minify is removing HTML comments.
A quick search showed my its probably not possible to mark comments to they wont removed with cloudfliar. On top if this its a wordpress plugin so the issue is still relevant to all kinds of caching plugins that remove HTML comments.
So now my question is. Is there better method lazyloading iframes without HTML comments? I like to still somehow store the iframe in place ... well just as I am writing this I may be able to store the data to build a iframe in some random tag json encoded or something and then build the iframe on click.
Just came across this.
So this the <script> tag could be a good solution, no modification of data needed, but prevents the browser from doing anything with it.
HTML
<script type="text/html" class="arve-lazyload">
<iframe src="https://youtube.com/...?autoplay=1"></iframe>
</script>
jQuery
var lazyloaded_iframe = $('.arve-lazyload');
$( lazyloaded_iframe.html() ).insertAfter( lazyloaded_iframe );
The other method putting it into script was actually again causing W3Tc surround with with [CDATA] messing with my code.
This is my new and hopefully final method. I really like it. The data() gives me the attributes as it comes in. Little big on the HTML but I think finally I am save from caching plugins.
HTML
<div class="arve-lazyload" data-allowfullscreen="" data-class="arve-iframe fitvidsignore" data-frameborder="0" data-name="" data-sandbox="allow-scripts allow-same-origin" data-scrolling="no" data-src="https://www.youtube-nocookie.com/embed/w68VZ8C1Q24?iv_load_policy=3&modestbranding=1&rel=0&autohide=1&playsinline=1&autoplay=1"></div>
jQuery
lazyload = wrap.find('.arve-lazyload');
if ( lazyload.length ) {
$('<iframe></iframe>').attr( lazyload.data() ).insertAfter( lazyload );
}
I have browsed several Q&A regarding difficulties with enqueuing scripts (including jQuery) into Wordpress, and most seem to cover the trouble that the scripts are not being found at all.
I am pretty sure I cracked that nut ok, my scripts appear to be found and loading correctly, but they are not behaving as traditionally expected.
Here is a truncated snippet of the code I placed in my functions.php file in a child theme I created:
<?php
function adding_scripts() {
wp_register_script('custom_styles', get_template_directory_uri() . '/style.css');
wp_register_script('custom_scripts', get_stylesheet_directory_uri() . '/jQuery_scripts.js.php', array('jquery'));
wp_enqueue_script('custom_scripts');
wp_enqueue_script('custom_styles');
}
add_action( 'wp_enqueue_scripts', 'adding_scripts' );
?>
This has successfully enqueued my custom CSS & to a degree my custom jQuery... but the jQuery is not working as expected. The coding is rudimentary, on par with my abilities, but ought to work.
There has to be some specific Wordpress noConflict 'something' I am missing
jQuery(document).ready(function( $ ) {
var variable1 = $(".element1").width();
$(".element3").css({"width":variable1+"px"});
$(".element4").click(alert(variable1));
});
The variable is not being created, that is the first problem.
The 'click' event I originally created to do a test to see what the variable was and found something curious. When the page loads, the click even fires without a click on .element4.
The return is null in that alert.
So the questions are: Why aren't the variable being created as they would normally and Why is the click even listener triggered without a click event on .element4?
Well, as luck would have it, for an unknown reason(cache?) after about 8-10 hours after I enqueued the scripts the variables were being finally created. My alert test did return the element's width.
However, as stated in the comment, my click(); was still being spontaneously triggered with no click.
As a test I changed to .on("click",function(){}); and this seems to be working fine. I suppose that the jQuery library installed in Wordpress is not completely, totally the same as if linking to the remotely hosted one at jQuery or Google.
No matter, there is no further issue at this time, and while I did only half answer my own question, since I don't know the root causes of the issues in the first place, I guess half is close enough.
Brief
Imagine your first website vastly growing in the amount of code, however particular parts you want to globally modify such as a menu seen on every page. So I've taken my header and added it to it's own file and load it using:
// Load Header
$(".Header").load("assets/HTML/header.html");
So I've got my header, added it to it's own place to allow a bit of CMS to my website.
What Makes It Tick?
Dependant Files:
jquery-1.11.0.min.js
jquery-migrate-1.2.1.min.js
jquery-ui-1.10.3.custom.min.js
jquery.ui.widget.js
jquery.ui.selectmenu.js
In page script for drop downs and whatnot
The Problem
The header is loading presumably after all my scripts have loaded regardless of the several places I've tried and tested adding to fetch the header code.
I'm HOPING this is enough to insight some help, some possible problems many encounter as posting my link, it is massively subject to change! Please specify how I could make this question anymore local to Stackoverflow, however for now my live version can be found here.
I don't think that is good implementation of jQuerys load() method.
Have you tried using this pattern instead of using jquerys .ready()?
$(window).load(function(){
# your code
$(".Header").html(yourContent);
});
From jQuery API:
"Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready."
Just remember to put this statement outside of $(document).ready(function() { ... });.
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');
?>