I've written a function that makes sure an image is both big enough horizontally and vertically to fill it's parent element, and to do this I used a while loop. When I open the index.html file on my computer locally it loads fine but as soon as I upload it to my server and try to access it the page never loads.
Here's the Javascript:
$(document).ready(function() {
initialize();
}
function initialize() {
$("[data-type='parallax']").each(function() {
$(this).css('height', $(this).parent().height());
while (($(this).height() < $(this).parent().height()) || ($(this).width() < $(this).parent().width())) {
$(this).css('height', '+=1px');
}
});
}
Does anyone know why this is? I know it's the while loop I just don't understand why it works locally. Is there an easier way to approach this with CSS where the image is at least as tall and wide as the parent element but only as big as it needs to be.
you could use animate, check this Fiddle
code:
<script type="text/javascript">
$(document).ready(function() {
initialize();
})
function initialize() {
$("[data-type='parallax']").each(function() {
var wi=$(this).width()
var he=$(this).height()
var pW=$(this).parent().width()
var pH=$(this).parent().height()
if(wi<pW||he<pH){
$(this).animate({'width':pW+'px','height':pH+'px'},1000)
}
});
}
</script>
Related
Use case #1:The following demo, will load a zooming feature to images if the browser width is greater than 500px.
https://codepen.io/zuhocuyixu/pen/NYLZrY
<!-- Loading .js file with Head.js
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/headjs/1.0.3/head.js"></script>
<script>
if (window.innerWidth > 500) {
head.ready(document, function() {
head.load('https://cdnjs.cloudflare.com/ajax/libs/zooming/1.4.2/zooming.js', function() {
var ZoomingIsLoaded = true;
var zooming = new Zooming();
zooming.listen('.value-img');
});
});
}
else {
var ZoomingIsLoaded = false;
}
</script>
<script type="text/javascript">
var myVar="ReCheckIfZoomingShouldBeLoaded";
function ReCheckIfZoomingShouldBeLoaded() {
if (window.innerWidth > 500 && ZoomingIsLoaded == false) {
head.ready(document, function() {
head.load('https://cdnjs.cloudflare.com/ajax/libs/zooming/1.4.2/zooming.js', function() {
var zooming = new Zooming();
zooming.listen('.value-img');
var ZoomingIsLoaded = true;
});
});
}
}
</script>
Use case #2:If the width is less than 500px it will not load the zooming, although on browser resize it will check if the width has become greater than 500px and then load the zooming feature.
The issue is that once it loads the zooming features it is buggy and acts strange when closing it.
Any ideas how to fix this glitch?
Also if anyone has an idea how to unload the zooming feature if the browser width goes below 500px, that would be of great help.
So, I have this code and I have been trying to get the images to change accordingly with the screen size. I want it to keep checking the screen size and changing relatively.
Here is the code:
$(function(){
$.mbBgndGallery.buildGallery({
containment:"#home",
timer:4600,
effTimer:700,
controls:"#controls",
grayScale:false,
shuffle:false,
preserveWidth:false,
effect:"slideLeft",
effect:{enter:{left:"-100%",opacity:1},exit:{top:0,opacity:0}, enterTiming:"ease-in", exitTiming:"ease-in"},
images:[
"images/bb/Slider/slider-image-01.jpg",
"images/bb/Slider/slider-image-02.jpg",
"images/bb/Slider/slider-image-03.jpg",
"images/bb/Slider/slider-image-04.jpg",
"images/bb/Slider/slider-image-05.jpg"
],
onStart:function(){},
onPause:function(){},
onPlay:function(opt){},
onChange:function(opt,idx){},
onNext:function(opt){},
onPrev:function(opt){}
});
});
and here is the code to check for the screen size:
var width = $(window).width();
$(window).resize(function () {
if (width > 800){
} else if (width <=800){
}
});
Whenever I paste the code for the images within the code for the screen size, it breaks. What gives?
PS. The path for the images to be viewed are located in a different folder path:
Window screen:
images:[
"images/bb/Slider/slider-image-01.jpg",
"images/bb/Slider/slider-image-02.jpg",
"images/bb/Slider/slider-image-03.jpg",
"images/bb/Slider/slider-image-04.jpg",
"images/bb/Slider/slider-image-05.jpg"
]
Phone Screen Images
images:[
"images/bb/phoneslider/slider-image-01.jpg",
"images/bb/phoneslider/slider-image-02.jpg",
"images/bb/phoneslider/slider-image-03.jpg",
"images/bb/phoneslider/slider-image-04.jpg",
"images/bb/phoneslider/slider-image-05.jpg"
]
The docs (https://github.com/pupunzi/jquery.mb.bgndGallery/wiki) describe a method here: myGallery.changeGallery(array).
This allows you to change the gallery images at will - i.e on width change of your window...
So, inside of your window.resize method, you can call changeGallery and pass in the array of images for the screen size....
Thank you for the reply, your answer was very helpful. However, I believe I did something wrong as I broke everything...
This is the latest update on the code
I have added the $(window).resize(function() {..}) to the $(function() {..}) with myGallery, images are still no where to be seen. The myGallery was previous defined as $.mbBgndGallery.buildGallery before I changed it.
This is what it looks now:
$(function(){
myGallery = new mbBgndGallery({
containment:"#home",
timer:4600,
effTimer:700,
controls:"#controls",
grayScale:false,
shuffle:false,
preserveWidth:false,
effect:"slideLeft",
effect:{enter:{left:"-100%",opacity:1},exit:{top:0,opacity:0}, enterTiming:"ease-in", exitTiming:"ease-in"},
// If your server allow directory listing you can use:
// (however this doesn't work locally on your computer)
//folderPath:"testImage/",
// else:
images:[
"images/bb/Slider/slider-image-01.jpg",
"images/bb/Slider/slider-image-02.jpg",
"images/bb/Slider/slider-image-03.jpg",
"images/bb/Slider/slider-image-04.jpg",
"images/bb/Slider/slider-image-05.jpg"
],
onStart:function(){},
onPause:function(){},
onPlay:function(opt){},
onChange:function(opt,idx){},
onNext:function(opt){},
onPrev:function(opt){}
});
$(window).resize(function () {
var width = $(window).width();
if (width > 800){
var windowarray=[“images/bb/Slider/slider-image-01.jpg”,“images/bb/Slider/slider-image-02.jpg”,“images/bb/Slider/slider-image-03.jpg”,“images/bb/Slider/slider-image-04.jpg”,“images/bb/Slider/slider-image-05.jpg”];
myGallery.changeGallery(windowarray);
}
else if (width <=800){
var phonearray=[“images/bb/phoneslider/slider-image-01.jpg”,“images/bb/phoneslider/slider-image-02.jpg”,“images/bb/phoneslider/slider-image-03.jpg”,“images/bb/phoneslider/slider-image-04.jpg”,“images/bb/phoneslider/slider-image-05.jpg”];
myGallery.changeGallery(phonearray);
}
});
});
Of course I did it wrong since I never replaced the images within the function. I appologize for these noobie mistake, I am very new.
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.
I did a Google search and I cannot find a way to do a loading with percentage. Anyone know how I can find an example of that?
I need a preload for a website from 0-100 without bar, before show the content, but I cannot find any example.
I recommend this plugin. Its amazing
download from http://demo.inwebson.com/download/jpreloader.zip
see in action here http://www.inwebson.com/demo/jpreloader/
<script type="text/javascript" src="js/jpreLoader.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$('body').jpreLoader();
});
// ]]></script>
here are the links to new version jpreloader 2.1
http://demo.inwebson.com/download/jpreloader-v2.zip
http://www.inwebson.com/demo/jpreloader-v2/
If you mean you want to show the content only when it is fully loaded, you may try following two options:
1) wrap all content inside a <div id="wrapper" style="display:none;"></div> tag and on load complete event show it like this:
$(function(){
$("#wrapper").show();
});
2) If this still does not solves your purpose, you can load empty page and fetch content using ajax:
$(function(){
$.ajax({
.......//AJAX params
.......
success:function(msg){
$("#wrapper").html(msg);//DO NEEDFUL WITH THE RETURNED VALUE
});
});
EDIT: Using queryLoader script provided by gayadesign I was able to achieve some success :D
I had to made some changes to the queryLoader.js file from line 127 to 151. The changed script is as follows. Try it yourself.
$(QueryLoader.loadBar).css({
position: "relative",
top: "50%",
font-size:40px;
font-weight:bold;
line-height:50px;
height:50px;
width:100px;
});
},
animateLoader: function() {
var perc = (100 / QueryLoader.doneStatus) * QueryLoader.doneNow;
if (perc > 99) {
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 5000, "linear", function() {
$(this).html("<strong>100%</strong>");//MY EDIT
QueryLoader.doneLoad();
});
} else {
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 5000, "linear", function() {
//MY EDIT
$(this).html("<strong>"+Math.round(perc)+"%</strong>");
});
}
},
You can't.
As zzzzBov said, it isn't known how much content there will be, or what size that content is.
You could 'fake' it, with something like this (for the example I am using images):
var percentCounter = 0;
$.each(arrayOfImageUrls, function(index, value) {
$('<img></img>').attr('src', value) //load image
.load(function() {
percentCounter = (index / arrayOfImageUrls.length) * 100; //set the percentCounter after this image has loaded
$('#yourProgressContainer').text(percentCounter + '%');
});
});
As I mentioned this isn't a TRUE percentage of the sites loading, but a rough estimate of the images that have loaded, assuming each image is roughly the same size.
See this Project. It does what you want nicely.
http://www.gayadesign.com/diy/queryloader-preload-your-website-in-style/
The demo is hosted here
http://www.gayadesign.com/scripts/queryLoader/
Download it here
http://www.gayadesign.com/scripts/queryLoader/queryLoader.zip
I'm just working on my personal website, giving it a bit of a revamp.
I've implemented a sort of 'accordion' menu feature, where if a menu button is clicked, the "non-clicked" buttons disappear, and then the clicked button is moved to the top of the list, where then a panel animates down in which I will be putting text content.
In Firefox this works perfectly, however in IE and Chrome the button jumps to the top of the page and then animates to position, instead of animating from where it started from.
Anyone any ideas how to fix this?
Offending code:
function Accordion(e)
{
var o =
{
init: function()
{
o.button = e;
o.addClickHandler();
},
addClickHandler: function()
{
o.button.click(function(){
o.button.removeClass('unselected');
o.button.addClass('selected');
o.fader();
});
},
fader: function()
{
$j('.unselected').animate({opacity:0}, 1000);
var wait = setInterval(function() {
if(!$j('.unselected').is(":animated") ) {
clearInterval(wait);
o.shifter();
}
}, 100);
},
shifter: function()
{
o.button.css({'position':'absolute'});
o.button.animate({top:91}, 500, o.createInfoBox);
},
createInfoBox: function()
{
var buttonParent = o.button.parent();
buttonParent.append("<div class='infoBox'></div>");
$j('.infoBox').animate({height:390});
}
}
o.init();
return o;
}
}
The issue lies within the shifter function, where I'm setting the position to absolute and then animating so the desired effect can be achieved. I understand why it's doing this (presume it's just resetting itself to top:0 and then animating to top:91) but does anyone have a quick solution? It's late and it's doing my head in.
Much appreciated,
Dave
HAve you tried using the current position of the element when you switch it to absolute... for example:
function() {
var currentp = $(this).offset();
o.button.css({'position':'absolute', top: currentp.top});
o.button.animate({top:91}, 500, o.createInfoBox);
}
Note there are two different offset functions and im not sure which one you want use here so you might want to review the docs on that.
Also you could always just re-theme the jQuery-ui accordian and save yourself the trouble ;-)