I am having trouble with where to add some js/jquery. code. I have a js file in my wordpress template and want to add a simple piece of code to show/hide a div, although it breaks the exisiting js/jquery. Where do I add it in the file, so it will not break it and/or what is the way to structure this file?
Exisiting Wordpress JS file...
jQuery(document).ready(function( $ ) {
//VIDEO
var iframe = $('.videoPlayer')[0],
player = $f(iframe),
status = $('.status');
// When the player is ready, add listeners for pause, finish, and playProgress
player.addEvent('ready', function() {
status.text('ready');
player.addEvent('pause', onPause);
player.addEvent('finish', onFinish);
player.addEvent('playProgress', onPlayProgress);
});
// Call the API when a button is pressed
$('.playPause').bind('click', function() {
player.api($(this).text().toLowerCase());
console.log('clicked'); // triggers
player.api('paused', function(paused) {
console.log('inside paused'); // doesn't trigger
if (paused) {
player.api('play');
}
else {
player.api('pause');
}
});
});
var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
// IFRAME RESIZE
function videoWrapper() {
var winW = $(window).width();
var winH = $(window).height();
var winR = winH / winW;
var video = $("#videoContainer iframe");
// console.log( winW, winH, winR );
// ratio of original video
var vidR = video.attr("height") / video.attr("width");
// ratio of iframe
var ifrR = video.height() / video.width();
// ifrR nedds to be 0.65
//var diff = winW / (winH / vidR);
if ( winR > vidR ) {
// diff between current video height and winH
var diff = winH / (winW * vidR);
var newW = winW * diff;
var newH = winW * diff * 0.65;
video.css({
"width": newW,
"margin-left": 0 - (newW - winW) / 2,
"margin-top": 0 - (newH - winH) / 2,
"height": newH
});
} else {
video.css({
"width": winW,
"margin-left": "",
"margin-top": 0 - ( (winW * 0.65) - winH ) / 2,
"height": winW * 0.65
});
}
}
// VIDEO SELECT
if ( iOS ) {
$("#kvVideo").remove();
$("#kvVideoMobile").show();
}
// VIDEO MUTE
if ( iOS ) {
var iframe = document.getElementById("kvVideoMobile");
} else {
var iframe = document.getElementById("kvVideo");
}
var player = $f(iframe);
player.addEvent('ready', function() {
// player.api('setVolume', 0);
// $("#videoContainer").on('click', function() {
// // Play the video
// player.api('play');
// alert("play");
// });
});
function muteVideo () {
player.api('setVolume', 0);
mute = true;
$("#mute_button").hide();
$("#volume_button").show();
// console.log("mute");
}
function unmuteVideo () {
player.api('setVolume', 1);
mute = false;
$("#mute_button").show();
$("#volume_button").hide();
// console.log("unmute");
}
var mute = false;
$('#button').on("click", function(){
// console.log("button click");
if ( !mute ) {
muteVideo();
} else {
unmuteVideo();
}
});
// EVENTS
$(window).on("load", function(){
videoWrapper();
}).on("resize", function(){
videoWrapper();
sectionCalc();
});
});
The second part of code I want to add into the js file, so it will work with the code already there...
$(document).ready(function(){
$(".colophon").hide();
$(".newsletter").hide();
$("#colophon").click(function(){
$(".newsletter").hide();
$(".colophon").fadeToggle('slow');
});
$("#newsletter").click(function(){
$(".colophon").hide();
$(".newsletter").fadeToggle('slow');
});
});
Thanks!
I would create you own file and then enqueue it using WordPress's wp_enqueue_script() in your functions.php file
Related
I followed Paul Lewis's guide to debounce and requestAnimationFrame. I'm translating an image across the screen on scroll when it comes into view.
var bicycles = $('.tandem-bike', context),
lastScrollY = 0,
ticking = false;
function update() {
var windowHeight = window.innerHeight,
windowWidth = $(window).width(),
bikeTop = [];
bicycles.each( function (i, el) {
bikeTop[i] = $(this).offset();
});
bicycles.each(function(i, el) {
var position = bikeTop[i];
var fromTop = position.top - windowHeight;
var imgHeight = $(this).height();
// When this image scrolls into view.
if (lastScrollY > fromTop && lastScrollY < position.top + imgHeight && i == 1 ) { // 375 ~= height of image
var translate = Math.floor((lastScrollY - fromTop) / ((windowHeight + imgHeight + 300) / windowWidth));
console.log('add tp tranlate ', translate);
$(this).css('transform', 'translateX(' + (translate - 275) + 'px)');
}
});
ticking = false;
}
function onScroll() {
lastScrollY = window.scrollY;
requestTick();
}
function requestTick() {
if(!ticking) {
requestAnimationFrame(update);
ticking = true;
}
}
window.addEventListener('scroll', onScroll, false);
This works great and the bicycle-built-for-two slides effortlessly across the screen. However, I want the image to "bounce" when the user stops scrolling. I figure an easy way would be to add a class when the animation ends, and pull it off when the animation starts. The obvious place to do that is within the if block in requestTick().
if(!ticking) {
$('.tandem-bike').removeClass('bounce');
requestAnimationFrame(update);
$('.tandem-bike').addClass('bounce');
ticking = true;
}
or
if(!ticking) {
requestAnimationFrame(update);
$('.tandem-bike').addClass('bounce');
ticking = true;
} else {
$('.tandem-bike').removeClass('bounce');
}
}
Neither works, and I don't love then because I'm whole-sale adding classes to all the animated images on the page. (I would live with that if it worked)
I am trying to Pause and Resume the javascript by clicking on the page.
I have text scrolling that changes by fading in and out.
The solutions I found online were how to pause marquee's, but I think that solution doesn't apply since my code doesn't use marquee tags.
Also for my text scrolling I'm not showing text, but images.
I was wondering how could I go about pausing and resuming the images by clicking on the page?
<div id="menu">
<button id="start-stop">Start/stop</button>
</div>
<div id="random_text"></div>
</div>
<script type="text/javascript">
$(window).load(function() {
$(window).resize(function() {
var windowHeight = $(window).height();
var containerHeight = $(".container").height();
$(".container").css("top", (windowHeight / 2 - containerHeight * 0.7) + "px");
});
var textarray = [
"<img class=\"tall\" src=\"1.png\" alt=\"1\"></img><span class=\"by\">Example</span>" ,
"<img class=\"wide\" src=\"2.png\" alt=\"2\"></img><span class=\"by\">Example</span>",
"<img class=\"wide\" src=\"3.png\" alt=\"3\"></img><span class=\"by\">Example</span>",
"<img class=\"wide\" src=\"4.png\" alt=\"4\"></img><span class=\"by\">Example</span>",
];
var firstTime = true;
function RndText() {
var rannum = Math.floor(Math.random() * textarray.length);
if (firstTime) {
$('#random_text').fadeIn('fast', function() {
$(this).html(textarray[rannum]).fadeOut('fast');
});
firstTime = false;
}
$('#random_text').fadeOut('fast', function() {
$(this).html(textarray[rannum]).fadeIn('fast');
});
var windowHeight = $(window).height();
var containerHeight = $(".container").height();
// $(".container").css("top", (windowHeight / 2 - containerHeight * 0.7) + "px");
}
$(function() {
// Call the random function when the DOM is ready:
RndText();
});
var inter = setInterval(function() {
intervalRunning = true;
RndText();
}, 3000);
});
$(document).on('click', '#start-stop', function(){
if (intervalRunning) {
intervalRunning = false;
clearInterval(inter);
} else {
inter = setInterval(function() {
intervalRunning = true;
RndText();
}, 3000);
}
})
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
I've created a jsbin to show a basic solution.
Since you are using jQuery, I would change how everything is structured. I would wrap the code in $(document).ready, so that it fires once the DOM is ready.
Create a bool at the outset to track if the interval is running:
var running = false;
Create a handler for the interval to turn on or off as needed:
var handleInterval = function(){
if (running) {
running = false;
clearInterval(intObj);
} else {
intObj = setInterval(function(){
running = true;
RndText();
}, 1500);
}
};
Set a handler for the button:
$(document).on("click", "#pause_me", function(){
handleInterval();
});
Kick the whole thing off with a call to handleInterval:
handleInterval();
Currently I have a script which starts a progress bar the moment a user starts scrolling.
Is it possible to change this to when the user gets to 340px from the top of the page?
Here is a demo of my site: http://pixsols.com/test/wordpress/reading-progress/
Here is my current code:
(function ( $ ) {
$.fn.progressScroll = function(options) {
var settings = $.extend({
fontSize : 20,
color : '#009ACF',
height : '5px',
textArea : 'dark',
}, options);
// element state info
var docOffset = $(this).offset().top,
elmHeight = $(this).height(),
winHeight = $(window).height();
// listen for scroll changes
$(window).on('scroll', function() {
var docScroll = $(window).scrollTop(),
windowOffset = docOffset - docScroll,
viewedPortion = winHeight + docScroll - docOffset;
if($(window).scrollTop() > 0) {
if($('.scrollWrapper').hasClass('hidden')) {
$('.scrollWrapper').removeClass('hidden').hide();
$('.scrollWrapper').slideDown('slow');
}
} else {
$('.scrollWrapper').slideUp('slow');
$('.scrollWrapper').addClass('hidden');
}
if(viewedPortion < 0) { viewedPortion = 0; }
if(viewedPortion > elmHeight) { viewedPortion = elmHeight; }
// calculate viewed percentage
var viewedPercentage = viewedPortion / elmHeight;
// set percent in progress element
$('.scroll-bar').css('width', (viewedPercentage*100)+'%' );
});
var self = this;
$(window).on('resize', function() {
docOffset = $(self).offset().top;
elmHeight = $(self).height();
winHeight = $(window).height();
$(window).trigger('scroll');
});
$(window).trigger('scroll');
var $el = $('.scroll-bar').css(settings);
return $el;
};
}( jQuery ));
My guess would be to manipulate this:
windowOffset = docOffset - docScroll,
Probably you should add or subtract 320px from windowOffset. So for example"
windowOffset = docOffset - docScroll + 320,
I'm trying to set a height to a div that it's parent have. I've tried and when I use console.log() it's actually working. But the height doesn't set without a refresh.....
This is my function
// Set Hight
function fixingHeight() {
function setHeight() {
var windowWidth = window.innerWidth;
var latestPostsWrapperHeight = $('#latestPosts').height();
var tabPane = $('#latestPosts').find('.tab-pane');
var tabPaneLists = $('#latestPosts').find('.tab-pane').find('li a');
var popularPostsWrapperHeight = $('#popularPosts').height();
var profileWrapper = $('#popularPosts').find('.pofile-wrapper');
if(windowWidth > 767) {
$.each(tabPane, function() {
$(this).height(latestPostsWrapperHeight - 70);
});
$.each(tabPaneLists, function() {
$(this).height((latestPostsWrapperHeight - 70) / 5 - 1);
});
$.each(profileWrapper, function() {
$(this).outerHeight(popularPostsWrapperHeight);
});
}
//console.log(windowWidth);
}setHeight();
$(window).resize(function() {
setHeight();
});
}fixingHeight();
To handle window resize event, call the function $(window).resize outside of the function setHeight()
to call setHeight() on first load, use the jquery handler $(document).ready
This is the final code :
function setHeight() {
var windowWidth = window.innerWidth;
var latestPostsWrapperHeight = $('#latestPosts').height();
var tabPane = $('#latestPosts').find('.tab-pane');
var tabPaneLists = $('#latestPosts').find('.tab-pane').find('li a');
var popularPostsWrapperHeight = $('#popularPosts').height();
var profileWrapper = $('#popularPosts').find('.pofile-wrapper');
if(windowWidth > 767) {
$.each(tabPane, function() {
$(this).height(latestPostsWrapperHeight - 70);
});
$.each(tabPaneLists, function() {
$(this).height((latestPostsWrapperHeight - 70) / 5 - 1);
});
$.each(profileWrapper, function() {
$(this).outerHeight(popularPostsWrapperHeight);
});
}
console.log(windowWidth);
}
$(document).ready(function() {
setHeight();
});
$(window).resize(function() {
setHeight();
});
remove the function wrapper fixingHeight(), 'setHeight()' is enough
$(window).resize dont't run because it is in a function so this is not working without calling the function wrapper, so get it outside of the function.
as # joram say, you can call $(document).ready when your document finish loading, so is ready.
$(document).ready(function() {
setHeight();
});
$(window).resize(function() {
setHeight();
});
function setHeight() {
var windowWidth = window.innerWidth;
console.log(windowWidth);
var latestPostsWrapperHeight = $('#latestPosts').height();
var tabPane = $('#latestPosts').find('.tab-pane');
var tabPaneLists = $('#latestPosts').find('.tab-pane').find('li a');
var popularPostsWrapperHeight = $('#popularPosts').height();
var profileWrapper = $('#popularPosts').find('.pofile-wrapper');
if(windowWidth > 767) {
$.each(tabPane, function() {
$(this).height(latestPostsWrapperHeight - 70);
});
$.each(tabPaneLists, function() {
$(this).height((latestPostsWrapperHeight - 70) / 5 - 1);
});
$.each(profileWrapper, function() {
$(this).outerHeight(popularPostsWrapperHeight);
});
}
}
i used this http://www.netmagazine.com/tutorials/create-interactive-street-view-jquery tutorial to create an intro for one of our customers:
http://f-bilandia.de/kunstmann/bronski/
It used to work really good on all browsers. When I updated to the newest stable version of Firefox (FF 18.0.1) however, there is heavy flickering while changing the images.
When reading the release notes of the newest version, i saw that ff has a new Javascript engine and has improved image quality with a new HTML scaling algorithm. Maybe it's because of that? Other possible solutions?
Below you can see the code i've used:
$(document).ready(function(){
var $doc = $(document);
var $win = $(window);
// dimensions - we want to cache them on window resize
var windowHeight, windowWidth;
var fullHeight, scrollHeight;
var streetImgWidth = 1024, streetImgHeight = 640;
calculateDimensions();
var currentPosition = -1, targetPosition = 0;
var $videoContainer = $('.street-view');
var video = $('.street-view > img')[0];
var $hotspotElements = $('[data-position]');
// handling resize and scroll events
function calculateDimensions() {
windowWidth = $win.width();
windowHeight = $win.height();
fullHeight = $('#main').height();
scrollHeight = fullHeight - windowHeight;
}
function handleResize() {
calculateDimensions();
resizeBackgroundImage();
handleScroll();
}
function handleScroll() {
targetPosition = $win.scrollTop() / scrollHeight;
}
// main render loop
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
function animloop(){
if ( Math.floor(currentPosition*5000) != Math.floor(targetPosition*5000) ) {
currentPosition += (targetPosition - currentPosition) / 5;
render(currentPosition);
}
requestAnimFrame(animloop);
}
// rendering
function render( position ) {
// position the elements
var minY = -windowHeight, maxY = windowHeight;
$.each($hotspotElements,function(index,element){
var $hotspot = $(element);
var elemPosition = Number( $hotspot.attr('data-position') );
var elemSpeed = Number( $hotspot.attr('data-speed') );
var elemY = windowHeight/2 + elemSpeed * (elemPosition-position) * scrollHeight;
if ( elemY < minY || elemY > maxY ) {
$hotspot.css({'visiblity':'none', top: '-1000px','webkitTransform':'none'});
} else {
$hotspot.css({'visiblity':'visible', top: elemY, position: 'fixed'});
}
});
renderVideo( position );
}
function resizeBackgroundImage(){
// get image container size
var scale = Math.max( windowHeight/streetImgHeight , windowWidth/streetImgWidth );
var width = scale * streetImgWidth , height = scale * streetImgHeight;
var left = (windowWidth-width)/2, top = (windowHeight-height)/2;
$videoContainer
.width(width).height(height)
.css('position','fixed')
.css('left',left+'px')
.css('top',top+'px');
}
// video handling
var imageSeqLoader = new ProgressiveImageSequence( "street/vid-{index}.jpg" , 387 , {
indexSize: 4,
initialStep: 16,
onProgress: handleLoadProgress,
onComplete: handleLoadComplete,
stopAt: 1
} );
// there seems to be a problem with ie
// calling the callback several times
var loadCounterForIE = 0;
imageSeqLoader.loadPosition(currentPosition,function(){
loadCounterForIE++;
if ( loadCounterForIE == 1 ) {
renderVideo(currentPosition);
imageSeqLoader.load();
imageSeqLoader.load();
imageSeqLoader.load();
imageSeqLoader.load();
}
});
var currentSrc, currentIndex;
function renderVideo(position) {
var index = Math.round( currentPosition * (imageSeqLoader.length-1) );
var img = imageSeqLoader.getNearest( index );
var nearestIndex = imageSeqLoader.nearestIndex;
if ( nearestIndex < 0 ) nearestIndex = 0;
var $img = $(img);
var src;
if ( !!img ) {
src = img.src;
if ( src != currentSrc ) {
video.src = src;
currentSrc = src;
}
}
}
$('body').append('<div id="loading-bar" style="">Loading...</div>');
function handleLoadProgress() {
var progress = imageSeqLoader.getLoadProgress() * 100;
$('#loading-bar').css({width:progress+'%',opacity:1});
}
function handleLoadComplete() {
$('#loading-bar').css({width:'100%',opacity:0,display: "none"});
$("html, body").css("overflow", "auto");
$("html, body").css("overflow-x", "hidden");
$("nav").css("display", "block");
$("#preloader").fadeOut("slow");
$("#scroll-hint").css("display", "block");
}
$win.resize( handleResize );
$win.scroll( handleScroll );
handleResize();
animloop();
});
Inside your "render( position )" function the following lines seem like they should be refactored.
if ( elemY < minY || elemY > maxY ) {
$hotspot.css({'visiblity':'none', top: '-1000px','webkitTransform':'none'});
} else {
$hotspot.css({'visiblity':'visible', top: elemY, position: 'fixed'});
}
For one visibility is spelled wrong and there is no "none" value for it (it would be "hidden"). Just use "display" with "none" and "" values.
The "top", "webkitTransform", and "position" keys seem unnecessary. If the element is not visible there's no need to set the top, and why wouldn't the element always be fixed position?