i'm with a problem here: http://thehitz.com.br/loja.php
when the page loads, appears an AJAX ERROR alert but the script works. That alert only shows up when i put the javascript code in the html. I've looked into the code and tried to localize the factor that is making this annoing thing happen but didnt have luck on it. Help me, please.
<script type="text/javascript">
$(function() {
// the element we want to apply the jScrollPane
var $el = $('#conteudo-container').jScrollPane({
verticalGutter : -16
}),
// the extension functions and options
extensionPlugin = {
extPluginOpts : {
// speed for the fadeOut animation
mouseLeaveFadeSpeed : 500,
// scrollbar fades out after hovertimeout_t milliseconds
hovertimeout_t : 1000,
// if set to false, the scrollbar will be shown on mouseenter and hidden on mouseleave
// if set to true, the same will happen, but the scrollbar will be also hidden on mouseenter after "hovertimeout_t" ms
// also, it will be shown when we start to scroll and hidden when stopping
useTimeout : false,
// the extension only applies for devices with width > deviceWidth
deviceWidth : 980
},
hovertimeout : null, // timeout to hide the scrollbar
isScrollbarHover: false,// true if the mouse is over the scrollbar
elementtimeout : null, // avoids showing the scrollbar when moving from inside the element to outside, passing over the scrollbar
isScrolling : false,// true if scrolling
addHoverFunc : function() {
// run only if the window has a width bigger than deviceWidth
if( $(window).width() <= this.extPluginOpts.deviceWidth ) return false;
var instance = this;
// functions to show / hide the scrollbar
$.fn.jspmouseenter = $.fn.show;
$.fn.jspmouseleave = $.fn.fadeOut;
// hide the jScrollPane vertical bar
var $vBar = this.getContentPane().siblings('.jspVerticalBar').hide();
/*
* mouseenter / mouseleave events on the main element
* also scrollstart / scrollstop - #James Padolsey : http://james.padolsey.com/javascript/special-scroll-events-for-jquery/
*/
$el.bind('mouseenter.jsp',function() {
// show the scrollbar
$vBar.stop( true, true ).jspmouseenter();
if( !instance.extPluginOpts.useTimeout ) return false;
// hide the scrollbar after hovertimeout_t ms
clearTimeout( instance.hovertimeout );
instance.hovertimeout = setTimeout(function() {
// if scrolling at the moment don't hide it
if( !instance.isScrolling )
$vBar.stop( true, true ).jspmouseleave( instance.extPluginOpts.mouseLeaveFadeSpeed || 0 );
}, instance.extPluginOpts.hovertimeout_t );
}).bind('mouseleave.jsp',function() {
// hide the scrollbar
if( !instance.extPluginOpts.useTimeout )
$vBar.stop( true, true ).jspmouseleave( instance.extPluginOpts.mouseLeaveFadeSpeed || 0 );
else {
clearTimeout( instance.elementtimeout );
if( !instance.isScrolling )
$vBar.stop( true, true ).jspmouseleave( instance.extPluginOpts.mouseLeaveFadeSpeed || 0 );
}
});
if( this.extPluginOpts.useTimeout ) {
$el.bind('scrollstart.jsp', function() {
// when scrolling show the scrollbar
clearTimeout( instance.hovertimeout );
instance.isScrolling = true;
$vBar.stop( true, true ).jspmouseenter();
}).bind('scrollstop.jsp', function() {
// when stop scrolling hide the scrollbar (if not hovering it at the moment)
clearTimeout( instance.hovertimeout );
instance.isScrolling = false;
instance.hovertimeout = setTimeout(function() {
if( !instance.isScrollbarHover )
$vBar.stop( true, true ).jspmouseleave( instance.extPluginOpts.mouseLeaveFadeSpeed || 0 );
}, instance.extPluginOpts.hovertimeout_t );
});
// wrap the scrollbar
// we need this to be able to add the mouseenter / mouseleave events to the scrollbar
var $vBarWrapper = $('<div/>').css({
position : 'absolute',
left : $vBar.css('left'),
top : $vBar.css('top'),
right : $vBar.css('right'),
bottom : $vBar.css('bottom'),
width : $vBar.width(),
height : $vBar.height()
}).bind('mouseenter.jsp',function() {
clearTimeout( instance.hovertimeout );
clearTimeout( instance.elementtimeout );
instance.isScrollbarHover = true;
// show the scrollbar after 100 ms.
// avoids showing the scrollbar when moving from inside the element to outside, passing over the scrollbar
instance.elementtimeout = setTimeout(function() {
$vBar.stop( true, true ).jspmouseenter();
}, 100 );
}).bind('mouseleave.jsp',function() {
// hide the scrollbar after hovertimeout_t
clearTimeout( instance.hovertimeout );
instance.isScrollbarHover = false;
instance.hovertimeout = setTimeout(function() {
// if scrolling at the moment don't hide it
if( !instance.isScrolling )
$vBar.stop( true, true ).jspmouseleave( instance.extPluginOpts.mouseLeaveFadeSpeed || 0 );
}, instance.extPluginOpts.hovertimeout_t );
});
$vBar.wrap( $vBarWrapper );
}
}
},
// the jScrollPane instance
jspapi = $el.data('jsp');
// extend the jScollPane by merging
$.extend( true, jspapi, extensionPlugin );
jspapi.addHoverFunc();
});
</script>
Well if you look at the console, you can see that there is a Ajax post request that is failing:
"NetworkError: 405 Method Not Allowed - http://thehitz.com.br/jcart/js/jcart.min.js"
Related
I'm building a WordPress Gutenburg block with Slick Slider that works on the front end, but not working or initializing in the editor.
I learned why from the great answer from #Sally CJ at https://wordpress.stackexchange.com/questions/391371/how-to-load-an-additional-script-for-a-block-in-the-block-editor.
I'm using a modified version of her accordion code to initialize the slider:
jQuery(document).ready(function(){
function initSlider( selector ) {
jQuery( selector ).slick({
dots: true,
infinite: true,
slidesToShow: 3,
slidesToScroll: 3
});
console.log( 'slider initialized' );
}
var targetNode = document.querySelector('#editor');
function initObserver( selector, targetNode ) {
const observer = new MutationObserver( ( mutations, observer ) => {
for ( let mutation of mutations ) {
if ( 'childList' === mutation.type && mutation.addedNodes[0] &&
// Good, the added node has a slider div.
jQuery( selector, mutation.addedNodes[0] ).length >= 1
) {
// Convert the div to a slick slider.
initSlider( mutation.addedNodes[0] );
}
}
} );
observer.observe( targetNode || document.getElementById( 'editor' ), {
childList: true,
subtree: true,
} );
return observer;
}
jQuery( function ( $ ) {
// Setup slider for existing .wp-block-slider in the current DOM.
initSlider( '.wp-block-slider' );
// Observe slider insertions in the block editor.
$( '#editor' ).length && initObserver( '.wp-block-slider' );
} );
} );
This works on the front end but not working or initializing in the editor, even though the script is being loaded with no errors.
Any ideas?
Thanks!
In my code, I am trying to execute a function that would change the defaultView of my fullCalendar based on the screen size. However, this only executes when a user loads in the screen size that I currently set it to.
I tried to view it on another screen to see if my else or : would execute and it did, but it only works once you refresh it on screen you are in. I would go to my developer tools/inspect element and drag the window to my desire screen size, but it still wouldn't execute.
Is there an improvement I can do in my code that I code or something that I am missing? I would love to learn from this as this is my first time trying out something crazy with the fullCalendar.
$(document).ready(function () {
$('#calendar').fullCalendar({
defaultView: $(window).width() < 765 ? 'basicDay':'agendaWeek',
header: {
left: "prev,next today",
center: "title",
right: "listMonth, month,agendaWeek,agendaDay",
},
displayEventTime: false,
editable: false,
eventRender: function(calEvent, element, view) {
// Check if the checkboxes already are added to FullCalendar
var checkboxPresent = false;
if( $('.calendar').find(".checkboxContainer").length == 1 ){
checkboxPresent = true;
}
if ( calEvent.title == "Title 1" ) {
element.css('background-color', '#44804C').addClass("normal");
if( checkboxPresent && !$("#normal").is(":checked") ){
element.hide();
}
}
else if (calEvent.title == "Title 2" ) {
element.css('background-color', '#804478').addClass("event");
if( checkboxPresent && !$("#event").is(":checked") ){
element.hide();
}
}
},
events: 'load.php',
});
// Create Checkboxes
var checkboxContainer = $("<div class='mb-3 checkboxContainer'><div class='d-flex flex-row'><label>Normal</label><input type='checkbox' id='normal' class='mx-3' checked></div><div class='d-flex flex-row'><label for='normal'>Event</label><input type='checkbox' id='event' class='mx-3' checked></div></div>");
// Append it to FullCalendar.
$(".fc-toolbar").before(checkboxContainer);
// Click handler
$("#calendar").on("click", "input[type='checkbox']", function(){
if($(this).is(":checked")){
$('#calendar').find("."+$(this).attr("id")).show();
}else{
$('#calendar').find("."+$(this).attr("id")).hide();
}
});
});
You can use this event hook which is triggered whenever the calendar is resized: https://fullcalendar.io/docs/windowResize
$(document).ready(function () {
$('#calendar').fullCalendar({
defaultView: $(window).width() < 765 ? 'basicDay':'agendaWeek',
windowResize: (arg) => {this.changeView($(window).width() < 765 ? 'basicDay':'agendaWeek')},
});
};
You might need to replace this. with a variable assigned to FullCalendar itself, something like:
$(document).ready(function () {
let FC = FullCalendar.Calendar({
defaultView: $(window).width() < 765 ? 'basicDay':'agendaWeek',
windowResize: (arg) => { FC.changeView($(window).width() < 765 ? 'basicDay':'agendaWeek') },
});
$('#calendar') = FC;
};
Here's my code :
if ($('document').scrollTop() < 0) {
//Automatic Scroll
setTimeout(function () {
$('html, body').animate({
scrollTop: $('.main-header').offset().top - 0
}, 1800, 'easeInOutQuad');
},8000);
}
If a user does not scroll, the page scrolls automatically to a certain div.
But I don't know how to trigger when a user do not scroll.
Thanks for your help !
To detect if a user hasn't scrolled, what I would do is set up a hasScrolled variable.
var hasScrolled = false;
Then change that variable to 'true' if the user scrolls:
document.addEventListener("scroll", function(){ hasScrolled = true; });
Then do your setTimeout to see if, in 8 seconds, the user has scrolled, and if not, do your thing:
setTimeout(triggerScroll,8000);
And in your triggerScroll function, the first line could be if (hasScrolled) return so that it doesn't run if they've scrolled
https://jsfiddle.net/eergdw3v/
try this
document.body.scrollTop === 0
You need to create a timer at the scroll event using setTimeout
function setUnscrollEvent( scrollTimeout, callback )
{
$( window).scroll(function() {
if ( window.scrollTimer )
{
clearTimeout( window.scrollTimer ); //if the scroll has already started then clear the timeout
}
window.scrollTimer = setTimeout( function(){
callback(); //invoke the callback in case scroll has been idle for srollTimeout ms
}, scrollTimeout );
});
}
You need to invoke it this way
setUnscrollEvent( 100, function(){
console.log( "no scrolling for 100ms" );
});
DEMO
function setUnscrollEvent( scrollTimeout, callback )
{
$( window).scroll(function() {
if ( window.scrollTimer )
{
clearTimeout( window.scrollTimer ); //if the scroll has already started then clear the timeout
}
window.scrollTimer = setTimeout( function(){
callback(); //invoke the callback in case scroll has been idle for srollTimeout ms
}, scrollTimeout );
});
}
setUnscrollEvent( 100, function(){
console.log( "no scrolling for 100ms" );
});
.container
{
width: 1000px;
height: 1000px;
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
</div>
let scrollHandler = function(e) {
//do your stuff
}
$(window).on("scroll",scrollHandler);
That will detect scrolling for you, to answer the question in your title. I don't follow what you're trying to say under your code though
Export your function, so that you can call it when you want :
if ($('document').scrollTop() < 0) {
//Automatic Scroll
setTimeout(triggerScroll,8000);
}
function triggerScroll() {
$('html, body').animate({
scrollTop: $('.main-header').offset().top - 0
}, 1800, 'easeInOutQuad');
}
// Manual trigger :
triggerScroll();
I'm experiencing some strange behavior with a jQuery plugin that I wrote. Basically, the plugin makes a sidebar element stick to the top of the browser window when scrolling through the blog post that the sidebar belongs to. This should only happen when the window reaches a certain size (768px) or above (the plugin detects this by checking the float style of the sidebar).
Everything works as expected...until you resize the browser from large -- sidebar is sticky -- to small -- sidebar should not be sticky. My onResize function supposedly removes the scroll event handler and only adds it back if the startQuery is true (so, if the sidebar float value is something other than none). I've double and triple checked through the console: everything is working correctly as far as I can tell. I even added console.log('scroll') to the onScroll function and it doesn't show up when the event handler is supposed to be removed, but my sidebar is still turning sticky when I scroll through the blog posts.
You can see the problem in action here. To recreate the steps:
Resize your browser window to less than 768px wide and visit the page. See that the .share-bar element inside each blog post does not move as you scroll. 'scroll' is not logged in the console.
Resize your browser window to 768px or larger. See that the .share-bar element becomes sticky as you scroll through each blog post, then sticks to the bottom of the post as you scroll past it. 'scroll' is logged in the console.
Resize your browser window to less than 768px. See that the .share-bar element becomes sticky as you scroll through each blog post. 'scroll' is not logged in the console.
It's almost as if the event handler is removed, but the elements aren't updating or something. I'm sure I'm missing something fundamental, but I've researched and tried all sorts of fixes for $(window).scroll event problems and none of them are working here.
My call to plugin:
$('.share-bar').stickySides({
'wrapper': '.post-wrapper',
'content': '.entry-content' });
Plugin code:
;( function ( $, window, document, undefined ) {
var settings;
var throttled;
$.fn.stickySides = function( options ) {
settings = $.extend( {}, $.fn.stickySides.defaults, options );
// Store sidebars
settings.selector = this.selector;
settings.startQuery = '$("' + settings.selector + '").css(\'float\') != \'none\'';
// Create debounced resize function
var debounced = _.debounce( $.fn.stickySides.onResize, settings.wait );
$(window).resize( debounced );
// Create throttled scroll function
throttled = _.throttle( $.fn.stickySides.onScroll, settings.wait );
// Only continue if the start query is true
if ( eval(settings.startQuery) == true ) {
$(window).on( 'scroll.stickySides', throttled );
}
return this;
};
// Define default settings
$.fn.stickySides.defaults = {
wrapper: 'body',
content: '.content',
wait: 100,
startQuery: ''
};
$.fn.stickySides.onResize = function ( ) {
$(window).off( 'scroll.stickySides' );
// Only continue if the start query is true
if ( eval(settings.startQuery) == true ) {
$(window).on( 'scroll.stickySides', throttled );
} else {
var sides = $(settings.selector);
sides.each ( function () {
var elem = $(this);
var content = elem.siblings( settings.content );
if ( elem.css('position') == 'fixed' || elem.css('position') == 'absolute' ) {
elem.css( 'position', 'static' );
}
if ( content.css('margin-left') != '0px' ) {
content.css( 'margin-left', 0 );
}
});
}
};
$.fn.stickySides.onScroll = function ( ) {
console.log('scroll');
var sides = $(settings.selector);
// Check each sidebar
sides.each ( function () {
var elem = $(this);
var content = elem.siblings( settings.content );
var wrapper = elem.closest( settings.wrapper );
var elemHeight = elem.height();
var wrapperHeight = wrapper.height();
// Only continue if the wrapper is taller than the sidebar
if ( elemHeight >= wrapperHeight ) {
return;
} else {
var wrapperFracs = wrapper.fracs(function (fracs) {
// Only continue if the wrapper is in view
if ( fracs.visible == 0 ) {
return;
} else {
// Check if the wrapper extends beyond the top of
// the viewport
var wrapperSpaceTop = fracs.rects.element.top;
// If it does, change sidebar position as appropriate
if ( wrapperSpaceTop > 0 ) {
var visibleWrapper = fracs.rects.document.height;
// If the visible portion of the wrapper is smaller
// than the height of the sidebar...
if ( visibleWrapper <= elemHeight ) {
// ...position the sidebar at the bottom
// of the wrapper
if ( wrapperSpaceTop != 0 ) {
elem.css('position', 'absolute').css( 'top', (wrapperHeight - elemHeight) + content.position().top + 'px' );
}
// Otherwise, move sidebar to appropriate position
} else {
elem.css('position', 'fixed').css('top', 0);
}
content.css('margin-left', elem.outerWidth());
} else {
elem.css('position', 'static');
content.css('margin-left', 0);
}
}
});
}
});
};
} )( jQuery, window, document );
PS: I would use an existing plugin, but I didn't see one that got really close to the functionality I need here; feel free to point one out if you know of one. I haven't tested outside of Mac yet. And yes, I know some of the page elements don't flow very well on mobile -- ex: site header & nav -- and there are some other missing items unrelated to this problem. I'm waiting for some feedback from my client before I can address that.
Happens every time. Shortly after I ask for help, I figure it out on my own. ;)
The problem was in the fracs function inside the onScroll function. I didn't realize it called its own resize/scroll handlers, so those weren't getting unbound when I removed my scroll handler. I just reworked the plugin to take advantage of the fracs library's handlers instead of calling my own scroll handler:
;( function ( $, window, document, undefined ) {
var settings;
var throttled;
$.fn.stickySides = function( options ) {
settings = $.extend( {}, $.fn.stickySides.defaults, options );
// Store sidebars
settings.selector = this.selector;
settings.startQuery = '$("' + settings.selector + '").css(\'float\') != \'none\'';
if ( eval( settings.startQuery ) == true ) {
$.fn.stickySides.doFracs();
}
// Create debounced resize function
var debounced = _.debounce( $.fn.stickySides.onResize, settings.wait );
$(window).resize( debounced );
return this;
};
// Define default settings
$.fn.stickySides.defaults = {
wrapper: 'body',
content: '.content',
wait: 100,
startQuery: ''
};
$.fn.stickySides.doFracs = function ( ) {
var sides = $(settings.selector);
// Check each sidebar
sides.each ( function () {
var elem = $(this);
var content = elem.siblings( settings.content );
var wrapper = elem.closest( settings.wrapper );
var elemHeight = elem.height();
var wrapperHeight = wrapper.height();
// Only continue if the wrapper is taller than the sidebar
if ( elemHeight >= wrapperHeight ) {
return;
} else {
var wrapperFracs = wrapper.fracs( $.fn.stickySides.fracsCallback );
}
});
}
$.fn.stickySides.unbindFracs = function ( ) {
var sides = $(settings.selector);
// Check each sidebar
sides.each ( function () {
var elem = $(this);
var content = elem.siblings( settings.content );
var wrapper = elem.closest( settings.wrapper );
if ( elem.css('position') == 'fixed' || elem.css('position') == 'absolute' ) {
elem.css( 'position', 'static' );
}
if ( content.css('margin-left') != '0px' ) {
content.css( 'margin-left', 0 );
}
wrapper.fracs('unbind');
});
}
$.fn.stickySides.fracsCallback = function ( fracs ) {
// Only continue if the wrapper is in view
if ( fracs.visible == 0 ) {
return;
} else {
var wrapper = $(this);
var elem = wrapper.find(settings.selector);
var content = elem.siblings( settings.content );
var elemHeight = elem.height();
var wrapperHeight = wrapper.height();
// Check if the wrapper extends beyond the top of
// the viewport
var wrapperSpaceTop = fracs.rects.element.top;
// If it does, change sidebar position as appropriate
if ( wrapperSpaceTop > 0 ) {
var visibleWrapper = fracs.rects.document.height;
// If the visible portion of the wrapper is smaller
// than the height of the sidebar...
if ( visibleWrapper <= elemHeight ) {
// ...position the sidebar at the bottom
// of the wrapper
if ( wrapperSpaceTop != 0 ) {
elem.css('position', 'absolute').css( 'top', (wrapperHeight - elemHeight) + content.position().top + 'px' );
}
// Otherwise, move sidebar to appropriate position
} else {
elem.css('position', 'fixed').css('top', 0);
}
content.css('margin-left', elem.outerWidth());
} else {
elem.css('position', 'static');
content.css('margin-left', 0);
}
}
}
$.fn.stickySides.onResize = function ( ) {
// Only continue if the start query is true
if ( eval(settings.startQuery) == true ) {
$.fn.stickySides.doFracs();
} else {
$.fn.stickySides.unbindFracs();
}
};
} )( jQuery, window, document );
Voila! Problem solved.
I run the following code on a page (#home) that should smoothly inject a slider or if the page container is under 480px leave the page as is.
I cannot get the resize event to work 100% smoothly.
If I reduce the window the script (js.slide.js) wont get triggered but the content will be loaded in (slide.php). If I continue to reduce the window a little extra it will all work ok.
Could anyone please advise as to how I could get this working smoothly. The code is as follows
$(document).ready(function(){
if ($("#home").length > 0 ){
var homeSlideShow = {
$promoArea: $('#promo-area'),
$currentContent: $('#promo-area').contents(),
$pageContainer: $('.page'),
init: function(){
var hSS = homeSlideShow;
if (hSS.$pageContainer.width() > 480 ){
hSS.setTheSlideShow();
} else{
hSS.$promoArea.html(hSS.$currentContent);
}
},
setTheSlideShow: function(){
var hSS = homeSlideShow;
$.getScript(myscript_wp_vars.temp_dir + '/js/slide.js', function(){
hSS.$promoArea.load(myscript_wp_vars.temp_dir + '/libs/slide.php #c4u-slide',
function(){
var options = {
preloader: false,
nextButton: true,
prevButton: true,
animateStartingFrameIn: true,
transitionThreshold: 250
};
var sequence = $("#sequence").sequence(options).data("sequence"),
$slideShow = $("#c4u-slide");
});
});
}
};
//
// Check page size
//
if (homeSlideShow.$pageContainer.width() > 480 ){
homeSlideShow.setTheSlideShow();
}
//
// On window resize
//
$(window).resize(function() {
homeSlideShow.init();
});
}// END home.length
});//End $(document).ready(function()
Thanks in advance for any assistance or advice.
Cheers
Noel
window.resize event is triggered multiple times, depending of browser's behaviour. I'll suggest you to try this:
var timeoutResize;
$(window).resize(function(){
if(typeof timeoutResize != 'undefined') clearTimeout(timeoutResize);
timeoutResize = setTimeout(function(){homeSlideShow.init();},50);
});