jquery responsive wordpress slider height change - javascript

I have a premium wordpress theme which came with a built in full page slider. It integrates nicely into my website but it displays full page and the information underneath is being lost. The slider is responsive to the window size, I'd like it to be only 60%. Please can someone help:
(function ($) {
"use strict";
$.fn.maximage = function (settings, helperSettings) {
var config;
if (typeof settings == 'object' || settings === undefined) config = $.extend( $.fn.maximage.defaults, settings || {} );
if (typeof settings == 'string') config = $.fn.maximage.defaults;
/*jslint browser: true*/
$.Body = $('body');
$.Window = $(window);
$.Scroll = $('html, body');
$.Events = {
RESIZE: 'resize'
};
this.each(function() {
var $self = $(this),
preload_count = 0,
imageCache = [];
/* --------------------- */
// #Modern
/*
MODERN BROWSER NOTES:
Modern browsers have CSS3 background-size option so we setup the DOM to be the following structure for cycle plugin:
div = cycle
div = slide with background-size:cover
div = slide with background-size:cover
etc.
*/
var Modern = {
setup: function(){
if($.Slides.length > 0){
// Setup images
for(var i in $.Slides) {
// Set our image
var $img = $.Slides[i];
// Create a div with a background image so we can use CSS3's position cover (for modern browsers)
$self.append('<div class="mc-image ' + $img.theclass + '" title="' + $img.alt + '" style="background-image:url(\'' + $img.url + '\');' + $img.style + '" data-href="'+ $img.datahref +'">'+ $img.content +'</div>');
}
// Begin our preload process (increments itself after load)
Modern.preload(0);
// If using Cycle, this resets the height and width of each div to always fill the window; otherwise can be done with CSS
Modern.resize();
}
},
preload: function(n){
// Preload all of the images but never show them, just use their completion so we know that they are done
// and so that the browser can cache them / fade them in smoothly
// Create new image object
var $img = $('<img/>');
$img.load(function() {
// Once the first image has completed loading, start the slideshow, etc.
if(preload_count==0) {
// Only start cycle after first image has loaded
Cycle.setup();
// Run user defined onFirstImageLoaded() function
config.onFirstImageLoaded();
}
// preload_count starts with 0, $.Slides.length starts with 1
if(preload_count==($.Slides.length-1)) {
// If we have just loaded the final image, run the user defined function onImagesLoaded()
config.onImagesLoaded( $self );
}else{
// Increment the counter
preload_count++;
// Load the next image
Modern.preload(preload_count);
}
});
// Set the src... this triggers begin of load
$img[0].src = $.Slides[n].url;
// Push to external array to avoid cleanup by aggressive garbage collectors
imageCache.push($img[0]);
},
resize: function(){
// Cycle sets the height of each slide so when we resize our browser window this becomes a problem.
// - the cycle option 'slideResize' has to be set to false otherwise it will trump our resize
$.Window
.bind($.Events.RESIZE,
function(){
// Remove scrollbars so we can take propper measurements
$.Scroll.addClass('mc-hide-scrolls');
// Set vars so we don't have to constantly check it
$.Window
.data('h', Utils.sizes().h)
.data('w', Utils.sizes().w);
// Set container and slides height and width to match the window size
$self
.height($.Window.data('h')).width($.Window.data('w'))
.children()
.height($.Window.data('h')).width($.Window.data('w'));
// This is special noise for cycle (cycle has separate height and width for each slide)
$self.children().each(function(){
this.cycleH = $.Window.data('h');
this.cycleW = $.Window.data('w');
});
// Put the scrollbars back to how they were
$($.Scroll).removeClass('mc-hide-scrolls');
});
}
}
Thanks in advance. James

Generally, the themes are very customizable on the admin panel. So, you should check it out before you changing it by hand.
If you dont find for customization on the admin panel (and on the theme developer page), as you may be know, when the themes are responsive they are using some framework like bootstrap, foundation, whatever. And then, the slider have to have a css class like "large-12", it should be modified to change its size, for example "large-8", then the slider size will be 8/12.
I hope it help you!

Related

particle-slider logo won't resize in Safari

I'm loading a front-end site from Wordpress using a HTML 5 Blank Child Theme. I have a logo effect using particle slider for when I have a screen size of >960px; for screen sizes <960px I have a flat logo image. It all works fine on both Firefox and Google Chrome but when I re-size between logos on Safari the page has to be refreshed manually (i.e. by pressing cmd+r) before the PS effect shows again. The code was sourced from an original question I posted here - Original Stack Q&A
Here's the javascript code I'm now using -
particle-slider.php
<?php /* Template Name: particle-slider */ ?>
<!-- particle-slider template -->
<div id="particle-slider">
<div class="slides">
<div class="slide" data-src="<?php echo home_url(); ?>/wp-content/uploads/2017/10/havoc_logohight.png"></div>
</div>
<canvas class="draw" style="width: 100%; height: 100%;"></canvas>
</div>
<script type="text/javascript">
var ps = new ParticleSlider({ 'width':'1400', 'height': '600' });
// patch nextFrame to track failure/success
var nextFrameCalled = false;
ps.oldNextFrame = ps.nextFrame;
ps.nextFrame = function () {
try {
ps.oldNextFrame.apply(this, arguments);
nextFrameCalled = true;
} catch (e) {
console.log(e);
nextFrameCalled = false;
}
};
var addEvent = function (object, type, callback) {
if (object.addEventListener) {
object.addEventListener(type, callback, false);
} else if (object.attachEvent) {
object.attachEvent("on" + type, callback);
} else {
object["on" + type] = callback;
}
};
var oldWidth = window.innerWidth;
addEvent(window, 'resize', function () {
var newWidth = window.innerWidth;
if (newWidth >= 960 && oldWidth < 960) {
console.log("Restarting particle slider " + newWidth);
ps.resize();
if (!nextFrameCalled)
ps.nextFrame(); // force restart animation
else {
// ensure that nextFrameCalled is not still true from previous cycle
nextFrameCalled = false;
setTimeout(function () {
if (!nextFrameCalled)
ps.nextFrame(); // force restart animation
}, 100);
}
}
oldWidth = newWidth;
});
</script>
<div id="logo"> <img src="<?php echo home_url(); ?>/wp-content/uploads/2017/10/havoc_logo.png"> </div>
<!-- particle-slider template -->
I need the same effect as is seen on this site here - where the logo switches from particle to static as the page is re-sized. The particle logo re-appears perfectly.
All other relevant code is linked to the original question as nothing has changed. I'm not seeing anything in the console to suggest why it's not working.
The resize event can fire multiple times, and within that event anything you put in a setTimeout will get called after the current code block has executed. It's hard to say for sure without picking apart ParticleSlider, but I think the mix of global variables (nextFrameCalled, oldWidth) and callbacks firing out of your expected order is the cause.
I think the intention is to debounce the forced restart - you want to call ParticleSlider.nextFrame() but if it's already been called you want to wait 100ms first.
Looking at the answer you've adapted for this question that appears to be a workaround for the canvas element not being visible on requestAnimationFrame - that might still not be available after 100ms or after the ParticleSlider.nextFrame() has been called multiple times in an attempt to get it to fire.
From your original question and selected answer I think you need to ParticleSlider.init() to reset the component, but the flashing you're seeing is due to the fact that it takes a while to run every time it's called. ParticleSlider.nextFrame() doesn't take as long (and uses requestAnimationFrame to avoid jank) but doesn't create the canvas on resize in Safari.
So, to fix:
Use ParticleSlider.init()
Debounce the resize event so you're not firing it lots of times
Fire it once a short delay after the user has stopped firing resize events.
Code will be something like:
var timeout = null;
window.addEventListener('resize', function() {
// Clear any existing debounced re-init
clearTimeout(timeout);
// Set up a re-init to fire in 1/2 a secound
timeout = setTimeout(function() {
ps.init();
}, 500);
});
You'll still see the flash and the delay as the component re-initialises, but only once.
I'd add that ParticleSlider has been deprecated by the authors and replaced with NextParticle - probably to fix these kinds of issues (in fact it has specific features to handle resizing). As it is a paid for component I'd suggest asking them for the help with this, as you should get your money's worth (or switch to an open source component where you can fix these bugs yourself).
So, I've finally figured this out by retracing my steps using the Q&A from before. Previously there seemed to be an issue with some of the sample links but one appears to work now - example.
I went into the page inspector and noticed a few differences between the code firing this example and the one in the actual answer that was causing the logo to flicker like a light bulb. This is the code I have now put into the wordpress site -
<script type="text/javascript">
//wait until the DOM is ready to be queried
(function() {//document.addEventListener('DOMContentLoaded', function() { //DOM-ready callback
var ps, timeout;
var img1 = new Image();
img1.src = '<?php echo home_url(); ?>/wp-content/uploads/2017/10/havoc_logohight.png';//havoc_logo_e6os2n.png';
var imgs = [ img1 ];
handlePS();
window.addEventListener('resize', function() {
//https://davidwalsh.name/javascript-debounce-function
if (timeout) { //check if the timer has been set
clearTimeout(timeout); //clear the timer
}
//set a timer
timeout = setTimeout(handlePS, 250);
});
function handlePS() {
if (document.body.clientWidth >= 960) {
//check if ps is assigned as an instance of the ParticleSlider
if (ps != undefined && typeof ps !== null) {
ps.init(); //refresh the particle slider since it exists
console.log('called init on ps');
} else {
if (window.location.search.indexOf('d=1') > -1) {
debugger;
}
//otherwise create a new instance of the particle slider
ps = new ParticleSlider({
width: 1400,
height: 600,
imgs: imgs
});
}
}
else {
//when the flat logo is displayed, get rid of the particle slider instance
// delete ps;
ps = null;
}
}
})();
</script>
It now works fine across all the main browsers - Chrome/Safari/Firefox. It still feels a bit clunky as it pushes the rest of the page down whilst it is re-sizing and it takes probably a few seconds more than I'd like - not sure if there's a timer option to speed the reanimation up? Otherwise, everything is working fine.

JavaScript: Set scroll position variable according to media queries

I am working on a fade-in/out-effect-on-scroll on a web project.
On my js I have to set a certain value for the scroll position i. e. the offset to make the effect kick in.
The problem:
The offset value cannot be applied to all kinds of devices due to
different heights.
Questions (hierarchic):
How to make the static values dynamic and variable to the device
height/media queries?
How can you generally slim down the code?
How can I trigger an additional slide-slightly-from-right/left to the
effect?
Here is the code:
// ---### FOUNDATION FRAMEWORK ###---
$(document).foundation()
// ---### FADE FX ###---
// ## SECTION-01: fade out on scroll ##
$(window).scroll(function(){
// fade out content a
$(".j-fadeOut").css("opacity", 1 - $(window).scrollTop() / 470);// 470 should be variable
// ## SECTION-02: fade in/out on scroll bottom ##
var offset = $('.j-fadeOut-2').offset().top;
console.log('offset: '+offset);
console.log('window: '+$(window).scrollTop())
if($(window).scrollTop() > offset)
{
// fade out top part of content b
$(".j-fadeOut-2").css("opacity", 1-($(window).scrollTop() - offset)/520);// 520 should be variable
// fade in bottom part of content c
$(".j-fadeIn").css("opacity", 0 + ($(window).scrollTop() - offset)/ 1100);// 1100 should be variable
}
});
See here for JavaScript Media Queries
You can use window.matchMedia to perform media queries in JavaScript. Example:
var mediaQuery = window.matchMedia( "(min-width: 800px)" );
The result will be stored as a boolean in mediaQuery.matches, i.e.
if (mediaQuery.matches) {
// window width is at least 800px
} else {
// window width is less than 800px
}
You can use multiple of these to suit your different device widths. Using the standard Bootstrap buckets:
var sizes = ['1200px', '992px', '768px', '480px']; // standard Bootstrap breakpoints
var fadeOutAs = [470, 500, 530, 560]; // this corresponds to your content a fadeout variable. Modify as required per screen size
var fadeOutBs = [520, 530, 540, 550]; // content B fadeout
var fadeOutCs = [1100, 1200, 1300, 1400]; // content C fadeout
var fadeOutA = 0;
var fadeOutB = 0;
var fadeOutC = 0;
for (i = 0; i < sizes.length; i++) {
var mediaQuery = window.matchMedia( "(min-width: " + sizes[i] + ")" );
if (mediaQuery.matches) {
fadeOutA = fadeOutAs[i];
fadeOutB = fadeOutBs[i];
fadeOutC = fadeOutCs[i];
}
}
Hope this helps

Position element in centre of visible viewport window with overflow-y:scroll

I've rather roughly built this website which uses an effect similar to the iOS Safari tab view to look at various pages of a virtual book. Everything is working fine apart from the fact that I can't centre each page in the visible viewport. For example if you scroll down to the final 'page' and click on it, it jumps to the top of the document, instead of staying in the centre of the visible viewport.
I think this is to do with the fact that the scrollable div uses overflow-y:scroll, but I just can't figure out for the life of me how to fix the problem.
Any help would be greatly appreciated!!
Here's my jQuery:
jQuery(document.body).on('click', '.page', function() { //Change to touchstart
// Generate number between 1 + 2
var randomClass = 3;
var randomNumber = Math.round(Math.random() * (randomClass - 1)) + 1;
// Initialise & Random Number
jQuery(this).addClass("activated").addClass('scaled-' + randomNumber);
// Exiting - Reset All
jQuery(document.body).on('click', '.activated', function() { //Change to Touchstart
jQuery(this).removeClass("activated scaled-1 scaled-2 scaled-3");
});
});
And here is a jsfiddle with all my code in it so you can get a better idea of what I'm trying to achieve.
https://jsfiddle.net/ontu1ngq/
Thanks!
You need to get the amount that #wrapper has been scrolled, so that you can use that to set the top of the .page accordingly. Then, when you remove the .activated class, you will just need to remove the inline top style.
jQuery(document.body).on('click', '.page', function() {
var randomClass = 3;
var randomNumber = Math.round(Math.random() * (randomClass - 1)) + 1;
jQuery(this).addClass("activated").addClass('scaled-' + randomNumber);
var wrapper_scrollTop = $("#wrapper").scrollTop(); //gets amount scrolled
var half_wrapper = $("#wrapper").height()*(0.5); //50% of wrapper height
jQuery(this).css("top",half_wrapper+wrapper_scrollTop);
jQuery(document.body).on('click', '.activated', function() {
jQuery(this).removeClass("activated scaled-1 scaled-2 scaled-3");
jQuery(this).css("top","") //returns top to original value specified in css
});
});
Check out this working fiddle: https://jsfiddle.net/tardhepc/1/

javascript not hiding element when opening webpage

jQuery(window).scroll( function(){
/* Check the location of element */
jQuery('.logoscrollbg').each( function(i){
var logo = jQuery(this).outerHeight();
var position = jQuery(window).scrollTop();
/* fade out */
if( position > logo ){
jQuery(this).animate({'opacity':'1'},100);
}else{ jQuery(this).animate({'opacity':'0'},100);}
});
});
Above is my script for a class (the header) with should blend in when the page is being scrolled down and blend out when you are on the top of the page, with other words the start.
I don't understand javascript at all, but I do a little php and I was wondering if someone could help me write there a elseif tag and later make the else tag so that is the page is loaded the class(.logoscrollbg) isn't visible and when u start scrolling it gets visible and when you get to the top it gets invisivle again :)
The script works like this right now: when I enter the site it shows the bar(bad), later when scrolling it stays or well is there(good), then when getting to top again it fades out(good).
The code inside your scroll event needs to be run when the page is loaded as well as when it scrolls.
jQuery(function() {
// object to hold our method
var scrollCheck = {};
// define and call our method at once
(scrollCheck.check = function() {
// only need to get scrollTop once
var logo, position = jQuery(window).scrollTop();
/* Check the location of element */
jQuery('.logoscrollbg').each(function() {
logo = jQuery(this).outerHeight();
/* fade out or in */
// cleaned this up a bit
jQuery(this).animate({'opacity': position > logo ? 1 : 0}, 100);
});
})();
jQuery(window).scroll(function(){
// call our method
scrollCheck.check();
});
});
It looks to me like this will only fire when you scroll. Try updating your js to this:
jQuery(window).on('scroll, load', function() {
/* Check the location of element */
jQuery('.logoscrollbg').each( function(i){
var logo = jQuery(this).outerHeight();
var position = jQuery(window).scrollTop();
/* fade out */
if( position > logo ){
jQuery(this).animate({'opacity':'1'},100);
}else{ jQuery(this).animate({'opacity':'0'},100);}
});
});
*note: You may want to fire the callback on document load instead of window.

Phaser loading images using object function

Hi everyone I'm new to Phaser, its really cool but I'm having an issue trying to use add.sprite, I have an array filled with the game information and I'm trying to paste the pictures into the map on the screen the code is as follows. It is the full game code however I'll elaborate further. I have an array called 'paises' which has the name of each country as well as the population and a little bit of more information. I'm trying to add a function for adding the sprites (images) so that later on I can just use a for loop to add all of them to the screen. This function is known as addSprite();
The error message that I get is that the location of the image that the addSprite function will use is considered as undefined since it doesnt know where 'venezuela' inside the following code is located:
addSprite:function(){ this.add.sprite(85,2,'venezuela');}
Its the same issue for the other addSprite functions.
I'm a little new to prototyping so that might be it. Also tried adding the array paises inside the create function to give it time to load the assets but no luck.
BasicGame = {};
BasicGame.Game = function (game) {};
var paises = [
{
name:'venezuela',
population: 30620404,
brandRecognition: 0,
clients:0,
sales:0,
addSprite:function(){
this.add.sprite(85,2,'venezuela');
}},
{
name:'colombia',
population:48264000,
brandRecognition:0,
clients:0,
sales:0,
addSprite:function(){
this.add.sprite(40,2,'colombia');
}},
{
name:'ecuador',
population:16309000,
brandRecognition:0,
clients:0,
sales:0,
addSprite:function(){
this.add.sprite(25,80,'ecuador');}
},
{
name:'guayana',
population:747884,
brandRecognition:0,
clients:0,
sales:0,
addSprite:function(){
this.add.sprite(164,26,'guayana');}
}];
BasicGame.Game.prototype = {
init: function () {
// set up input max pointers
this.input.maxPointers = 1;
// set up stage disable visibility change
this.stage.disableVisibilityChange = true;
// Set up the scaling method used by the ScaleManager
// Valid values for scaleMode are:
// * EXACT_FIT
// * NO_SCALE
// * SHOW_ALL
// * RESIZE
// See http://docs.phaser.io/Phaser.ScaleManager.html for full document
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
// If you wish to align your game in the middle of the page then you can
// set this value to true. It will place a re-calculated margin-left
// pixel value onto the canvas element which is updated on orientation /
// resizing events. It doesn't care about any other DOM element that may
// be on the page, it literally just sets the margin.
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = false;
// Force the orientation in landscape or portrait.
// * Set first to true to force landscape.
// * Set second to true to force portrait.
this.scale.forceOrientation(true, false);
// Sets the callback that will be called when the window resize event
// occurs, or if set the parent container changes dimensions. Use this
// to handle responsive game layout options. Note that the callback will
// only be called if the ScaleManager.scaleMode is set to RESIZE.
this.scale.setResizeCallback(this.gameResized, this);
// Set screen size automatically based on the scaleMode. This is only
// needed if ScaleMode is not set to RESIZE.
this.scale.setScreenSize(true);
// Re-calculate scale mode and update screen size. This only applies if
// ScaleMode is not set to RESIZE.
this.scale.refresh();
},
preload: function () {
// Here we load the assets required for our preloader (in this case a
// background and a loading bar)
this.load.image('logo', 'asset/phaser.png');
this.load.image('brasil','asset/brasil.png');
this.load.image('colombia','asset/colombia.png');
this.load.image('venezuela','asset/venezuela.png');
this.load.image('ecuador','asset/ecuador.png');
this.load.image('peru','asset/peru.png');
this.load.image('guayana','asset/guayana.png');
this.load.image('surinam','asset/surinam.png');
this.load.image('guayanaFrancesa','asset/guayanaFrancesa.png');
this.load.image('brasil','asset/brasil.png');
this.load.image('chile','asset/chile.png');
this.load.image('bolivia','asset/bolivia.png');
this.load.image('argentina','asset/argentina.png');
this.load.image('paraguay','asset/paraguay.png');
this.load.image('uruguay','asset/uruguay.png');
this.load.image('menu','asset/menu.png');
this.load.image('oceano','asset/oceano.jpg');
},
create: function () {
var oceano = this.add.sprite(0,0,'oceano');
var menu = this.add.sprite(450,50,'menu');
for(var i=0;i<3;i++){
paises[i].addSprite();
}
},
gameResized: function (width, height) {
// This could be handy if you need to do any extra processing if the
// game resizes. A resize could happen if for example swapping
// orientation on a device or resizing the browser window. Note that
// this callback is only really useful if you use a ScaleMode of RESIZE
// and place it inside your main game state.
}};
Hi guys just got it to work, the solution involved moving the function outside the object and just saving the parameters inside the object (the x,y and file name). I also made the paises variable a global one. It might not be the most elegant solution but it does what I need it to do. I'll post the code in case someone else can benefit from it.
var paises = [
{
name:'venezuela',
population: 30620404,
brandRecognition: 0,
clients:0,
sales:0,
x:85,
y:2
},
{
name:'colombia',
population:48264000,
brandRecognition:0,
clients:0,
sales:0,
x:40,
y:2
},
{
name:'ecuador',
population:16309000,
brandRecognition:0,
clients:0,
sales:0,
x:25,
y:80
},
{
name:'guayana',
population:747884,
brandRecognition:0,
clients:0,
sales:0,
x: 164,
y:26
}];
BasicGame = {
};
BasicGame.Game = function (game) {
};
BasicGame.Game.prototype = {
init: function () {
// set up input max pointers
this.input.maxPointers = 1;
// set up stage disable visibility change
this.stage.disableVisibilityChange = true;
// Set up the scaling method used by the ScaleManager
// Valid values for scaleMode are:
// * EXACT_FIT
// * NO_SCALE
// * SHOW_ALL
// * RESIZE
// See http://docs.phaser.io/Phaser.ScaleManager.html for full document
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
// If you wish to align your game in the middle of the page then you can
// set this value to true. It will place a re-calculated margin-left
// pixel value onto the canvas element which is updated on orientation /
// resizing events. It doesn't care about any other DOM element that may
// be on the page, it literally just sets the margin.
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = false;
// Force the orientation in landscape or portrait.
// * Set first to true to force landscape.
// * Set second to true to force portrait.
this.scale.forceOrientation(true, false);
// Sets the callback that will be called when the window resize event
// occurs, or if set the parent container changes dimensions. Use this
// to handle responsive game layout options. Note that the callback will
// only be called if the ScaleManager.scaleMode is set to RESIZE.
this.scale.setResizeCallback(this.gameResized, this);
// Set screen size automatically based on the scaleMode. This is only
// needed if ScaleMode is not set to RESIZE.
this.scale.setScreenSize(true);
// Re-calculate scale mode and update screen size. This only applies if
// ScaleMode is not set to RESIZE.
this.scale.refresh();
},
preload: function () {
// Here we load the assets required for our preloader (in this case a
// background and a loading bar)
this.load.image('logo', 'asset/phaser.png');
this.load.image('brasil','asset/brasil.png');
this.load.image('colombia','asset/colombia.png');
this.load.image('venezuela','asset/venezuela.png');
this.load.image('ecuador','asset/ecuador.png');
this.load.image('peru','asset/peru.png');
this.load.image('guayana','asset/guayana.png');
this.load.image('surinam','asset/surinam.png');
this.load.image('guayanaFrancesa','asset/guayanaFrancesa.png');
this.load.image('brasil','asset/brasil.png');
this.load.image('chile','asset/chile.png');
this.load.image('bolivia','asset/bolivia.png');
this.load.image('argentina','asset/argentina.png');
this.load.image('paraguay','asset/paraguay.png');
this.load.image('uruguay','asset/uruguay.png');
this.load.image('menu','asset/menu.png');
this.load.image('oceano','asset/oceano.jpg');
},
create: function () {
var oceano = this.add.sprite(0,0,'oceano');
var menu = this.add.sprite(450,50,'menu');
for(var i=0;i<3;i++){
this.add.sprite(paises[i].x,paises[i].y,paises[i].name);
}
},
gameResized: function (width, height) {
// This could be handy if you need to do any extra processing if the
// game resizes. A resize could happen if for example swapping
// orientation on a device or resizing the browser window. Note that
// this callback is only really useful if you use a ScaleMode of RESIZE
// and place it inside your main game state.
}
};

Categories