In this post I drop small code snippets that I’d like to share with you, but are too small to require an entire separately written post.
Check if CSS ‘sticky’ position elements are ‘stuck’
This small jQuery function checks if elements that are positioned as sticky (position: sticky;
) are, in fact, in their ‘stuck’ position. It’s a very simple check where the script checks if the element’s position is equal to its ‘top’ CSS variable. If it is, it adds the class you specify (argument className
), and if not, removes it.
$.fn.checkStuck = function (className) {
$(this).each(function() {
var t = $(this); //preselect
t.toggleClass(className, (parseInt(t.css('top'), 10) === t[0].getBoundingClientRect().top));
});
}
Usage
Watch for scrolling and apply it to the elements that are stuck. For Bootstrap, you could do:
$(document).on('scroll', function() { $('.position-sticky').checkStuck('stuck'); });
Note: I highly recommend you debounce the scrolling handler.
Quick WordPress Theme Switcher
This small PHP script allows you to switch to a (development) theme only for logged in admin users, and show the regular theme for visitors. Just create a PHP file, name it what you want and place it in /wp-content/plugins
, and change the $theme
variable in the code to the folder name of the theme you’re developing. Then activate or deactivate the plug-in when you want to switch (or switch back). Note: Make sure you keep the comment-part, as that will identify it as a plug-in to the WordPress core.
/*
Plugin Name: Theme Switch if Admin (live theme development)
Description: Display different theme to user if logged in as admin
Author: Klaas Leussink
*/
add_filter('template', 'change_theme');
add_filter('option_template', 'change_theme');
add_filter('option_stylesheet', 'change_theme');
function change_theme($theme) {
if ( current_user_can('manage_options') && !is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
$theme = 'my_development_theme_folder';
}
return $theme;
}
jQuery Doubleclick & tap
This jQuery script enables doubleclick and doubletap (mobile) behaviour, without the need for global variables. It does not rely on jQuery’s ‘dblclick’ handler, but needs to be binded to the regular ‘click’ event.
$(document).on('click', '#MyDoubleClickElement', function () {
var t = $(this), doubleClickInterval = 500; //set up base vars
var lastTouch = t.data('lastTouch') || 0, time = new Date().getTime(); //check when this element has been clicked last
t.data('lastTouch', time); //store this click time
if (time - lastTouch < doubleClickInterval && lastTouch !== 0) { //check if time between this and previous click exceeds the threshhold. If there is no last click registered, don't handle the callback
//do your stuff here (execute a callback)
alert("Double click!");
}
});
No Responses