My Script is not working in wordpress static site - javascript

I am working on my wordpress site, and i use a static page for my front/home page. I wanted to use parallax scrolling but i cant get my script to load and work.
I linked it in header like this:
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/scroll.js"></script>
and this is my scroll script:
(function($) {
$.fn.parallax = function(options) {
var windowHeight = $(window).height();
// Establish default settings
var settings = $.extend({
speed: 0.15
}, options);
// Iterate over each object in collection
return this.each( function() {
// Save a reference to the element
var $this = $(this);
// Set up Scroll Handler
$(document).scroll(function(){
var scrollTop = $(window).scrollTop();
var offset = $this.offset().top;
var height = $this.outerHeight();
// Check if above or below viewport
if (offset + height <= scrollTop || offset >= scrollTop + windowHeight) {
return;
}
var yBgPosition = Math.round((offset - scrollTop) * settings.speed);
// Apply the Y Background Position to Set the Parallax Effect
$this.css('background-position', 'center ' + yBgPosition + 'px');
});
});
}
}(jQuery));
$('.parallax-section-1').parallax({
speed : 0.15
});
I found some articles that i would have to use the functions.php and enque the script but i never did that before so im a bit lost, so any help would be highly appreciated.

First things first, lets load the script the "WordPress Way". This will actually help simplify troubleshooting.
To do that, edit your theme's functions.php file.
In that file, add this PHP code. Be sure it is between <?php opening / closing tags.
Typically, I'd recommend adding it to the end of the file, but if your file includes this ?> - that the code you add is before the ?>:
add_action('enqueue_scripts', 'my_custom_script');
function my_custom_script() {
// Be sure jQuery is loading
wp_enqueue_script('jquery');
// Load your script
wp_enqueue_script('my-parallax-script', get_template_directory_uri() . '/js/scroll.js', array('jquery'), FALSE, TRUE);
}
Now - once you do this, you will want to be sure that your script is in fact loading. To do that, visit the page, then do a VIEW SOURCE in your browser. When you view source, do a search of the code for "scroll.js" - if you find it, great. Click on the url (or copy / paste it into your browser window) and be sure that the script is referencing the right location. If not, you'll need to be sure to move the script to the right location, so the page will load it.
Next Step
You have a problem with your script that will not work in WordPress. You are referencing jQuery with the $ symbol, AND it appears that you are referencing an element directly, which means there's a good chance the element doesn't exist when the script will run, which means that it won't have the desired effect.
Instead, we need to do two things. Because WordPress loads jQuery in what's called no conflict mode, you need to reference it using jQuery, not $. AND you need to put your code into a document ready function.
Thankfully, jQuery offers a slick way of doing the document ready that exposes the $ inside of the document ready, for convenience:
// Shorthand version of "No-conflict-safe" document ready
jQuery(function($) {
// Inside here, we can use $ instead of jQuery
$('.parallax-section-1').parallax({
speed : 0.15
});
});
If it still does not work after all of this, then you need to open your console in your browser, and look for any javascript errors. They will help you identify what is going on, which is the first step to solving the problem.

Related

Prevent inline scripts loading until Jquery has been loaded

Ok, I have a Jquery script, its function is to determine the width of the window, onload. If the width is greater than 642px it calls .load() to load an image slider. The reason for this is mobile devices will neither be served the images or js required for the slider.
This worked fine when jquery was loaded in the head. Upon moving to the footer its breaking. The code is included from the index.php. Could this be whats causing it? I would have thought once php built the page jquery parsed the content?
It appears the code is parsed before the jquery is loaded. Can anyone suggest a way to get round this please?
I have thought of creating the code as pure JS or using a delayed load, but I cant seem to figure out how to get it working.
There must be much better solutions? I feel like I’m missing something very obvious..
contents of the included script:
<script type="text/javascript">
$(window).bind("load", function() {
// code here
$(window).width(); // returns width of browser viewport
var width = $(window).width();
if (width >= 642) {
$('.slider-content').load("templates/include/slider.php", function () {
$('.slider-content').show(200);
});
}
else {
//alert('small')
}
});
</script>
Thanks,
Adam
In some environments, you must use jQuery() instead of $(). See this question.
Other than that, your problem might have to do with the document not being complete yet or binding to an event that has already passed. Try this instead:
jQuery(document).ready( function($) {
// Your code goes here. (You can safely use the $() function inside here.)
});

Fixing a JavaScript conflict in Wordpress, help using wp_enqueue_script

I think (not 100% sure) that I am suffering from a javascript conflict. I am using a pluggin to generate a countdown clock on my WordPress page, and I am using some simple custom made javascript with jQuery to make a div appear and dissapear on the page at certain points of scrolling.
To make the appearing / dissapearing div work correctly I added two javascript calls into my header:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/test1.js"></script>
The first being the jquery library and the second being my custom script. After adding these lines of code to the header, the countdown clock stopped working on my website. Through a little debugging I have realized that it is the Google hosted script that is causing the clock not too work.
When I have the code for the Google hosted jquery library in my header I receive the following error: Error = Object [object Object] has no method 'jCountdown'
I believe the solution to this is using the wp_enqueue_script and wp_register_script in the functions.php file to add the two .js files I need, and removing the code from the header. However, I am un familiar with how these bits of code work and can not seem to figure it out. Below is the code I believe needs to be used in the functions.php file, but I have been unsuccessful in making it work.
function notSureWhatGoesHere() {
wp_register_script(notSureWhatGoesHere);
wp_enqueue_script(notSureWhatGoesHere);
}
add_action(notSureWhatGoesHere);
And here is a link to my test webpage: http://jltest.biz/test-1
Thank you so much for your help and time.
You have a Error = Object [object Object] has no method 'jCountdown'
Maybe your plugin hasn't loaded properly...
Remove the jQuery you added jQuery.1.10.2 so i am not supprised that it doesn't work..
PLUS - WordPress has already added a version of jQuery.1.8.3
Now, in your test file you have this
var startY = 840;
var stopY = 1900;
$(window).scroll(function(){
checkY();
});
function checkY()
{
console.log($(window).scrollTop());
if($(window).scrollTop() > startY && $(window).scrollTop() <= stopY)
{
console.log("Show");
$('.fixedDiv').fadeIn("slow");
}
else
{
console.log("Hide");
$('.fixedDiv').fadeOut();
}
}
checkY();
Wordpress uses jQuery.noConflict(); by default so you need to make sure you wrap your code in something like the following
(function( $ ) {
// Code Here....
}( jQuery ));

Scroll to div on link click

There are questions all over SO about this topic, but I've tried a ton of different scripts for this and I cannot get it to work with my site.
I am building a personal portfolio wordpress theme for myself, and would like to keep it a one page theme. What I want is when a user clicks a link on the navigation, the page scrolls down to that section. Easy right? No.
I don't know why it isn't working on my site, but I think it has to do with the script I am using for the scroll to fixed navigation.
Here is the script I am currently attempting to use to create this in-page navigation scrolling effect: http://css-tricks.com/snippets/jquery/smooth-scrolling/
And here is the script I am using to create the scroll to fixed navigation effect:
window.onscroll=function () {
var top = window.pageXOffset ? window.pageXOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
if(top > 640){
document.getElementById("nav").style.position = "fixed";
document.getElementById("nav").style.height="65px";
} else {
document.getElementById("nav").style.position = "relative";
document.getElementById("nav").style.height="65px";
}
}
You can view the site I am trying to do this on at http://www.tylerb.me
Are the two scripts contradicting each other and making one of them not work?
It would appear wordpress uses the jQuery.noConflict() method to prevent well.. conflicts from occurring. Because of the script conflicts(moo tools uses $ as well, for example), replace each $ with jQuery. This should fix your issue.. and I do mean in the code which calls the plugin, not the plugin itself.
Example:
//normal jquery method call:
$("element").method(etc);
//with noConflict code:
jQuery("element").method(etc);
UPDATE 1:
It would appear that you forgot to leave a particular $ alone. This line:
var target = jQuery(this.hash), target = this.hash;
Should be this:
var $target = jQuery(this.hash), target = this.hash;
This of course goes with any variable that begins with a $. Those ones should not be deleted.
The core of your issue is that jQuery is not loading.
Daedalus just got there before me. It's no conflict that's causing your issue. Just use jQuery rather than $.
This could prove useful to some.
Try using:
jQuery(document).ready(function($){
// do stuff here using $
});
instead of
$(document).ready(function($){
// do stuff here
});
This declares a local $ instead of conflicting with the previously declared.
It helped me lots of times.

jQuery infinite-scroll Not Triggering

I'm making a simple little website to apply a different formatting style to Reddit posts, I'm trying to add the infinite-scroll jQuery plugin but it doesn't do anything. I tried following the (very simple) instructions on the infinite-scroll page and when it didn't do anything I thought I must have entered something wrongly, but then I just copy/pasted the code from the Masonry/Infinite-Scroll example and it still didn't work. Masonry is working perfectly (finally) but I just can't figure out what is wrong with infinite-scroll. I understand the basics of jQuery and JavaScript, but obviously not as much as most of you people, so could you please help me out and let me know what is wrong? My site is live at reddit.ymindustries.com.
Thanks heaps, you guys have rarely failed me so far.
YM
EDIT: If there aren't enough images to fill up the page on the homepage, visit reddit.ymindustries.com/r/aww for more images.
EDIT 2: I believe I located the issue, it is described here: https://github.com/paulirish/infinite-scroll/issues/5
Now to figure out a fix...
EDIT 3: Added a little bit of a hack in to make it sort of work, but it just seems to loop the second page endlessly now. Hmm...
I think your problem is actually css. Make your page longer that client area height. add more images to $container
Point is, botom edge of your $container need to pass bottom of window so scroll event fires so infinite scroll can react on this event and calculate weather or not edge is reached
BTW, in same cases, for instance, when I shrink my window, the example you set is working.
=== UPDATE ===
I found some time to play with infinitescroll and here is final working script, just set pathParse method in your script
$(function () {
var $container = $('#itemContainer');
$container.imagesLoaded(function () {
$container.masonry({
itemSelector:'.item'
});
});
$container.infinitescroll({
navSelector:'.navigation', // selector for the paged navigation
nextSelector:'.navigation #next', // selector for the NEXT link (to page 2)
itemSelector:'.item', // selector for all items you'll retrieve
bufferPx:40,
debug:true,
columnWidth:function (containerWidth) {
return containerWidth / 5;
},
loading:{
finishedMsg:'No more pages to load.',
img:'http://i.imgur.com/6RMhx.gif'
},
pathParse: function(path,page){
return $(this.nextSelector).attr("href");
}
},
// trigger Masonry as a callback
function (newElements) {
// hide new items while they are loading
var $newElems = $(newElements).css({ opacity:0 });
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function () {
// show elems now they're ready
$newElems.animate({ opacity:1 });
$container.masonry('appended', $newElems, true);
});
//console.log("test (never fired :( )");
}
);
});
Now, since your next link will not update by it self (http://reddit.ymindustries.com/?after=t3_yh4av), you need to change the callback to pull out last element from ajax response and change next link... could be something like this
function (newElements) {
// hide new items while they are loading
var $newElems = $(newElements).css({ opacity:0 });
// ensure that images load before adding to masonry layout
// ======> if query parameter after=... is caring filename then do this
var lastImageUrl= $newElements[$newElements.length-1].attr("src");
var lastFileName= lastImageUrl.substring(lastImageUrl.lastIndexOf("/") +1, lastImageUrl.lastIndexOf("."));
$("#next").attr("href", "http://reddit.ymindustries.com/?after="+lastFileName);
$newElems.imagesLoaded(function () {
// show elems now they're ready
$newElems.animate({ opacity:1 });
$container.masonry('appended', $newElems, true);
});
//console.log("test (never fired :( )");
}
You also need to take care of wich version of infinite-scroll your using since if you use the ones that comes with masonry/isotope (version 2.0b2.110713), both need a little hack in order to call the function and not use the predefined array:
//old code, to be changed (line 489)
desturl = path.join(opts.state.currPage);
// new code
desturl = (typeof path === 'function') ? path(opts.state.currPage) : path.join(opts.state.currPage);
This is already fixed in the newer versions of infinite-scroll
I had the same problem with jQuery's "infinitescroll" and Masonry. You might just solve this by giving your page more initial items so that the plugin's scrolling detection kicks in.
In WordPress this is under the "Reading" settings. By default WordPress only opens 10 items at a time. You could increase that number to 100/page to be more sure the window will be full initially. I had some code here that was just horrible, turns out I just needed longer pages, not more code.
So it's difficult to test these plugins on large displays if you don't have enough images. Maybe the solution is to scale the images larger on large displays so you're more sure about getting your content below the fold.
If you think someone might get to your website with a really huge display, I'm not sure what the answer is other than showing more items/page and maybe adding $('#masonry').infinitescroll('retrieve'); to your footer to load an extra page just in case.

Javascript scrolling code

Here is a link to some code that i would like to implement.
http://jsfiddle.net/g7gYy/12/
I am having a bit of trouble working out where to place the code and to actually get it too work.
Here is an html file that I have uploaded: http://www.canning.co.nz/Game/testmarquee.html
Can I please have some help with this?
thanks
First you didnt added jquery lib to your page add it.
<script src="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Next put all your code in document ready because before document get ready your code get executed but elements are not ready to do some operations
$(document).ready(function() {
var $text = $('.text-to-scroll', $marquee);
var textWidth = $text.width();
var $marquee = $('#marquee');
var marqueeWidth = $marquee.width();
$marquee.css('height', $text.height());
function animateLoop()
{
//First lets put if out of view to the left
$text.css('left', -textWidth);
//Now it's out of view, change it's display from none to block
$text.css('display', 'block');
//Now we can animate it so that if scrolls across the screen
//http://api.jquery.com/animate/
$text.animate({ 'left' : marqueeWidth }, 10000, 'linear', animateLoop);
}
});
Your javascript file link is not good.
<script language="JavaScript" type="text/javascript" src="marquee.js">
make sure the marquee.js file is in the same folder as your testmarquee.html page.
Later Edit:
Ow, scratch that, i was wrong, Mateusz was in fact right.:D

Categories

Resources