Changing windows width with JQuery without reloading the page again - javascript

I have a JQuery rotator in my website with a slides images and I want to make the website responsive. I'm using CSS media queries to do it. I want to change the slide width (which defines in JS) when the windows width is less than 800px.
So long, I did something like this:
var responsiveSlideWidth;
if ($(window).width() < 800) {
responsiveSlideWidth = 700;
}
else {
responsiveSlideWidth = 960;
}
var defaults = {
container: '.rotatorWrapper',
animationduration: 1000,
slideWidth: responsiveSlideWidth
};
The problem is that it is working just after page reload. Thats means: if I resize the window size its is not working until I reload the page.
Any suggestions?
Thanks.
EDIT: My full code:
(function ($) {
$.fn.Rotator = function (options) {
var responsiveSlideWidth;
if ($(window).width() < 800) {
responsiveSlideWidth = 700;
}
else {
responsiveSlideWidth = 960;
}
var defaults = {
container: '.rotatorWrapper',
animationduration: 1000,
slideWidth: responsiveSlideWidth
};
options = $.extend(defaults, options);
elm = this;
var pageIndex = 0,
slideCount = 0;
var _init = function () {
slideCount = elm.find(options.container).children().children().length;
elm.find(options.container).children().width(slideCount * options.slideWidth);
_bindEvents();
_togglePager();
};
var _bindEvents = function () {
var jElm = $(elm);
jElm.find('.prev').on('click', _previous);
jElm.find('.next').on('click', _next);
};
var _next = function (e) {
e.preventDefault();
if (pageIndex >= 0 && pageIndex < slideCount - 1) {
pageIndex++;
elm.find(options.container).children().animate({
left: "-=" + options.slideWidth
}, options.animationduration);
}
_togglePager();
};
var _previous = function (e) {
e.preventDefault();
if (pageIndex <= slideCount) {
pageIndex--;
elm.find(options.container).children().animate({
left: "+=" + options.slideWidth
}, options.animationduration);
}
_togglePager();
};
var _togglePager = function () {
var $elm = $(elm);
var prev = $elm.find('.prev');
var next = $elm.find('.next');
console.log('slide count' + pageIndex + ' Page Index' + pageIndex)
if (pageIndex >= slideCount - 1) {
next.hide();
} else {
next.show();
}
if (pageIndex <= 0) {
prev.hide();
} else {
prev.show();
}
}
return _init(elm);
}
})(jQuery);

Related

How could I add the following to my mediawiki main page?

I would like to add this timeline gimmick https://codepen.io/alvarotrigo/pen/yLzBJaN to the main page in my medawiki. How might I go about importing it? I have a script that enables HTML, but I do not know how to enable the CSS or JS.
I am not really a programmer and just trying to figure out the best way to test this out.
here is the code:
`
(function ($) {
$(function () {
$(window).on('scroll', function () {
fnOnScroll();
});
$(window).on('resize', function () {
fnOnResize();
});
var agTimeline = $('.js-timeline'),
agTimelineLine = $('.js-timeline_line'),
agTimelineLineProgress = $('.js-timeline_line-progress'),
agTimelinePoint = $('.js-timeline-card_point-box'),
agTimelineItem = $('.js-timeline_item'),
agOuterHeight = $(window).outerHeight(),
agHeight = $(window).height(),
f = -1,
agFlag = false;
function fnOnScroll() {
agPosY = $(window).scrollTop();
fnUpdateFrame();
}
function fnOnResize() {
agPosY = $(window).scrollTop();
agHeight = $(window).height();
fnUpdateFrame();
}
function fnUpdateWindow() {
agFlag = false;
agTimelineLine.css({
top: agTimelineItem.first().find(agTimelinePoint).offset().top - agTimelineItem.first().offset().top,
bottom: agTimeline.offset().top + agTimeline.outerHeight() - agTimelineItem.last().find(agTimelinePoint).offset().top
});
f !== agPosY && (f = agPosY, agHeight, fnUpdateProgress());
}
function fnUpdateProgress() {
var agTop = agTimelineItem.last().find(agTimelinePoint).offset().top;
i = agTop + agPosY - $(window).scrollTop();
a = agTimelineLineProgress.offset().top + agPosY - $(window).scrollTop();
n = agPosY - a + agOuterHeight / 2;
i <= agPosY + agOuterHeight / 2 && (n = i - a);
agTimelineLineProgress.css({height: n + "px"});
agTimelineItem.each(function () {
var agTop = $(this).find(agTimelinePoint).offset().top;
(agTop + agPosY - $(window).scrollTop()) < agPosY + .5 * agOuterHeight ? $(this).addClass('js-ag-active') : $(this).removeClass('js-ag-active');
})
}
function fnUpdateFrame() {
agFlag || requestAnimationFrame(fnUpdateWindow);
agFlag = true;
}
});
})(jQuery);
`

Universal script for moving elements in DOM

I want to create a universal code for easy moving elements in DOM between desktop and mobile. It's not my idea as well as not my code. It was for Prestashop 1.7 only, but I want to change it for any project.
The idea is that you can wrap some code you want to move in an absolute different place on mobile with <div id="_desktop_some-block">Some content</div>, and place empty <div id="_mobile_some-block"></div> where you want to see it on mobile devices and when window reach (for ex.) 768px the HTML of the element will be moving to another one.
So here is an original code:
import $ from 'jquery';
import prestashop from 'prestashop';
prestashop.responsive = prestashop.responsive || {};
prestashop.responsive.current_width = window.innerWidth;
prestashop.responsive.min_width = 768;
prestashop.responsive.mobile = prestashop.responsive.current_width < prestashop.responsive.min_width;
function swapChildren(obj1, obj2)
{
var temp = obj2.children().detach();
obj2.empty().append(obj1.children().detach());
obj1.append(temp);
}
function toggleMobileStyles()
{
if (prestashop.responsive.mobile) {
$("*[id^='_desktop_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_desktop_', '_mobile_'));
if (target.length) {
swapChildren($(el), target);
}
});
} else {
$("*[id^='_mobile_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_mobile_', '_desktop_'));
if (target.length) {
swapChildren($(el), target);
}
});
}
prestashop.emit('responsive update', {
mobile: prestashop.responsive.mobile
});
}
$(window).on('resize', function() {
var _cw = prestashop.responsive.current_width;
var _mw = prestashop.responsive.min_width;
var _w = window.innerWidth;
var _toggle = (_cw >= _mw && _w < _mw) || (_cw < _mw && _w >= _mw);
prestashop.responsive.current_width = _w;
prestashop.responsive.mobile = prestashop.responsive.current_width < prestashop.responsive.min_width;
if (_toggle) {
toggleMobileStyles();
}
});
$(document).ready(function() {
if (prestashop.responsive.mobile) {
toggleMobileStyles();
}
});
Here is what I'm trying to do:
var windowWidth = $(window).innerWidth();
var windowMinWidth = 768;
var windowResponsiveMobile = windowWidth < windowMinWidth;
function swapChildren(obj1, obj2)
{
var temp = obj2.children().detach();
obj2.empty().append(obj1.children().detach());
obj1.append(temp);
}
function toggleMobileStyles()
{
if (windowResponsiveMobile) {
$("*[id^='_desktop_']").each(function(idx, el) {
var target = $('#' + el.replace('_desktop_', '_mobile_'));
if (target.length) {
swapChildren($(el), target);
}
});
} else {
$("*[id^='_mobile_']").each(function(idx, el) {
var target = $('#' + el.replace('_mobile_', '_desktop_'));
if (target.length) {
swapChildren($(el), target);
}
});
}
}
$(window).on('resize', function() {
var _cw = windowWidth;
var _mw = windowMinWidth;
var _w = $(window).innerWidth();
var _toggle = (_cw >= _mw && _w < _mw) || (_cw < _mw && _w >= _mw);
windowWidth = _w;
windowResponsiveMobile = windowWidth < windowMinWidth;
if (_toggle) {
toggleMobileStyles();
}
});
$(document).ready(function() {
if (windowResponsiveMobile) {
toggleMobileStyles();
}
});
Currently it doesn't work, but I don't see any errors in the console and it little bit confuse...
Please help me to finish it so it could work.
var windowWidth = $(window).innerWidth();
var windowMinWidth = 768;
var windowResponsiveMobile = windowWidth < windowMinWidth;
function swapChildren(obj1, obj2)
{
var temp = obj2.children().detach();
obj2.empty().append(obj1.children().detach());
obj1.append(temp);
}
function toggleMobileStyles()
{
if (windowResponsiveMobile) {
$("[id^='_desktop_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_desktop_', '_mobile_'));
if (target.length) {
swapChildren($(el), target);
}
});
} else {
$("[id^='_mobile_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_mobile_', '_desktop_'));
if (target.length) {
swapChildren($(el), target);
}
});
}
}
$(window).on('resize', function() {
var _cw = windowWidth;
var _mw = windowMinWidth;
var _w = $(window).innerWidth();
var _toggle = (_cw >= _mw && _w < _mw) || (_cw < _mw && _w >= _mw);
windowWidth = _w;
windowResponsiveMobile = windowWidth < windowMinWidth;
if (_toggle) {
toggleMobileStyles();
}
});
$(document).ready(function() {
if (windowResponsiveMobile) {
toggleMobileStyles();
}
});
Here is the updated code, you just removed the id in the target selector.

Uncaught TypeError: $(...).find(...).once is not a function in bootstrap/js/bootstrap.js?

I have installed bootstrap theme for building responsive theme then I installed jquery_update module as documentation in theme project and everything seems ok expect below js error appears in inspect elements console:
Uncaught TypeError: $(...).find(...).once is not a function in
bootstrap/js/bootstrap.js?o5l669
Any one please can help me?
this is the bootstrap.js:
/**
* #file
* bootstrap.js
*
* Provides general enhancements and fixes to Bootstrap's JS files.
*/
var Drupal = Drupal || {};
(function($, Drupal){
"use strict";
Drupal.behaviors.bootstrap = {
attach: function(context) {
// Provide some Bootstrap tab/Drupal integration.
$(context).find('.tabbable').once('bootstrap-tabs', function () {
var $wrapper = $(this);
var $tabs = $wrapper.find('.nav-tabs');
var $content = $wrapper.find('.tab-content');
var borderRadius = parseInt($content.css('borderBottomRightRadius'), 10);
var bootstrapTabResize = function() {
if ($wrapper.hasClass('tabs-left') || $wrapper.hasClass('tabs-right')) {
$content.css('min-height', $tabs.outerHeight());
}
};
// Add min-height on content for left and right tabs.
bootstrapTabResize();
// Detect tab switch.
if ($wrapper.hasClass('tabs-left') || $wrapper.hasClass('tabs-right')) {
$tabs.on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
bootstrapTabResize();
if ($wrapper.hasClass('tabs-left')) {
if ($(e.target).parent().is(':first-child')) {
$content.css('borderTopLeftRadius', '0');
}
else {
$content.css('borderTopLeftRadius', borderRadius + 'px');
}
}
else {
if ($(e.target).parent().is(':first-child')) {
$content.css('borderTopRightRadius', '0');
}
else {
$content.css('borderTopRightRadius', borderRadius + 'px');
}
}
});
}
});
}
};
/**
* Bootstrap Popovers.
*/
Drupal.behaviors.bootstrapPopovers = {
attach: function (context, settings) {
if (settings.bootstrap && settings.bootstrap.popoverEnabled) {
var elements = $(context).find('[data-toggle="popover"]').toArray();
for (var i = 0; i < elements.length; i++) {
var $element = $(elements[i]);
var options = $.extend(true, {}, settings.bootstrap.popoverOptions, $element.data());
$element.popover(options);
}
}
}
};
/**
* Bootstrap Tooltips.
*/
Drupal.behaviors.bootstrapTooltips = {
attach: function (context, settings) {
if (settings.bootstrap && settings.bootstrap.tooltipEnabled) {
var elements = $(context).find('[data-toggle="tooltip"]').toArray();
for (var i = 0; i < elements.length; i++) {
var $element = $(elements[i]);
var options = $.extend(true, {}, settings.bootstrap.tooltipOptions, $element.data());
$element.tooltip(options);
}
}
}
};
/**
* Anchor fixes.
*/
var $scrollableElement = $();
Drupal.behaviors.bootstrapAnchors = {
attach: function(context, settings) {
var i, elements = ['html', 'body'];
if (!$scrollableElement.length) {
for (i = 0; i < elements.length; i++) {
var $element = $(elements[i]);
if ($element.scrollTop() > 0) {
$scrollableElement = $element;
break;
}
else {
$element.scrollTop(1);
if ($element.scrollTop() > 0) {
$element.scrollTop(0);
$scrollableElement = $element;
break;
}
}
}
}
if (!settings.bootstrap || !settings.bootstrap.anchorsFix) {
return;
}
var anchors = $(context).find('a').toArray();
for (i = 0; i < anchors.length; i++) {
if (!anchors[i].scrollTo) {
this.bootstrapAnchor(anchors[i]);
}
}
$scrollableElement.once('bootstrap-anchors', function () {
$scrollableElement.on('click.bootstrap-anchors', 'a[href*="#"]:not([data-toggle],[data-target])', function(e) {
this.scrollTo(e);
});
});
},
bootstrapAnchor: function (element) {
element.validAnchor = element.nodeName === 'A' && (location.hostname === element.hostname || !element.hostname) && element.hash.replace(/#/,'').length;
element.scrollTo = function(event) {
var attr = 'id';
var $target = $(element.hash);
if (!$target.length) {
attr = 'name';
$target = $('[name="' + element.hash.replace('#', '') + '"');
}
var offset = $target.offset().top - parseInt($scrollableElement.css('paddingTop'), 10) - parseInt($scrollableElement.css('marginTop'), 10);
if (this.validAnchor && $target.length && offset > 0) {
if (event) {
event.preventDefault();
}
var $fakeAnchor = $('<div/>')
.addClass('element-invisible')
.attr(attr, $target.attr(attr))
.css({
position: 'absolute',
top: offset + 'px',
zIndex: -1000
})
.appendTo(document);
$target.removeAttr(attr);
var complete = function () {
location.hash = element.hash;
$fakeAnchor.remove();
$target.attr(attr, element.hash.replace('#', ''));
};
if (Drupal.settings.bootstrap.anchorsSmoothScrolling) {
$scrollableElement.animate({ scrollTop: offset, avoidTransforms: true }, 400, complete);
}
else {
$scrollableElement.scrollTop(offset);
complete();
}
}
};
}
};
})(jQuery, Drupal);
I have same issue and my solution is exclude bootstrap.js on my custom theme.
also you can alter bootstrap.js
Maybe The problem is because of two version ov jquery load on your page, inspect your javascript and if there is two version of jquery, let one exist and remove another.
In my case, there are 2 jquery files (core, theme). I removed it from theme. it works perfectly fine.

Rename a function after resizing screen

is possible to change a name of a function after resizing screen?
I have this
<div id="box1" data-same-height="blocks-resize">
where
data-same-height="blocks-resize"
is the function, and here's the javascript of that function.
$(document).ready(function() {
var equalize = function () {
var disableOnMaxWidth = 0; // 767 for bootstrap
var grouped = {};
var elements = $('*[data-same-height]');
elements.each(function () {
var el = $(this);
var id = el.attr('data-same-height');
if (!grouped[id]) {
grouped[id] = [];
}
grouped[id].push(el);
});
$.each(grouped, function (key) {
var elements = $('*[data-same-height="' + key + '"]');
elements.css('height', '');
var winWidth = $(window).width();
if (winWidth <= disableOnMaxWidth) {
return;
}
var maxHeight = 0;
elements.each(function () {
var eleq = $(this);
maxHeight = Math.max(eleq.height(), maxHeight);
});
elements.css('height', maxHeight + "px");
});
};
var timeout = null;
$(window).resize(function () {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(equalize, 250);
});
equalize();
});
It's possible to change that name (data-same-height) after resizing screen to 600px? or could be also the "blocks-resize" too
Thanks!
$(function(){
$(window).on("resize load", responsive);
})
var responsive = function() {
if(window.innerWidth < 600) {
//do your thing
} else {
//do something else.
}
}

Hover to click in wordpress menu

I used a theme that I changed to show sub menu horizontally, now I want to show sub menu onClick and not on hover, I'm not good at javascript but I think that this code is about the navigation menu:
var nav = {
init: function() {
// Add parent class to items with sub-menus
jQuery("ul.sub-menu").parent().addClass('parent');
var menuTop = 40;
var menuTopReset = 80;
// Enable hover dropdowns for window size above tablet width
jQuery("nav").find(".menu li.parent").hoverIntent({
over: function() {
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
// Setup menuLeft variable, with main menu value
var subMenuWidth = jQuery(this).find('ul.sub-menu').first().outerWidth(true);
var mainMenuItemWidth = jQuery(this).outerWidth(true);
var menuLeft = '-' + (Math.round(subMenuWidth / 2) - Math.round(mainMenuItemWidth / 2)) + 'px';
var menuContainer = jQuery(this).parent().parent();
// Check if this is the top bar menu
if (menuContainer.hasClass("top-menu")) {
if (menuContainer.parent().parent().parent().hasClass("top-bar-menu-right")) {
menuLeft = "";
} else {
menuLeft = "-1px";
}
menuTop = 30;
menuTopReset = 40;
} else if (menuContainer.hasClass("header-menu")) {
menuLeft = "-1px";
menuTop = 28;
menuTopReset = 40;
} else if (menuContainer.hasClass("mini-menu") || menuContainer.parent().hasClass("mini-menu")) {
menuTop = 40;
menuTopReset = 58;
} else {
menuTop = 44;
menuTopReset = 64;
}
// Check if second level dropdown
if (jQuery(this).find('ul.sub-menu').first().parent().parent().hasClass("sub-menu")) {
menuLeft = jQuery(this).find('ul.sub-menu').first().parent().parent().outerWidth(true) - 2;
}
jQuery(this).find('ul.sub-menu').first().addClass('show-dropdown').css('top', menuTop);
}
},
out:function() {
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
jQuery(this).find('ul.sub-menu').first().removeClass('show-dropdown').css('top', menuTopReset);
}
}
});
jQuery(".shopping-bag-item").live("mouseenter", function() {
var subMenuTop = 44;
if (jQuery(this).parent().parent().hasClass("mini-menu")) {
subMenuTop = 40;
}
jQuery(this).find('ul.sub-menu').first().addClass('show-dropdown').css('top', subMenuTop);
}).live("mouseleave", function() {
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
jQuery(this).find('ul.sub-menu').first().removeClass('show-dropdown').css('top', 64);
}
});
// Toggle Mobile Nav show/hide
jQuery('a.show-main-nav').on('click', function(e) {
e.preventDefault();
if (jQuery('#main-navigation').is(':visible')) {
jQuery('.header-overlay .header-wrap').css('position', '');
} else {
jQuery('.header-overlay .header-wrap').css('position', 'relative');
}
jQuery('#main-navigation').toggle();
});
jQuery(window).smartresize(function(){
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
var menus = jQuery('nav').find('ul.menu');
menus.each(function() {
jQuery(this).css("display", "");
});
}
});
// Set current language to top bar item
var currentLanguage = jQuery('li.aux-languages').find('.current-language span').text();
if (currentLanguage !== "") {
jQuery('li.aux-languages > a').text(currentLanguage);
}
},
hideNav: function(subnav) {
setTimeout(function() {
if (subnav.css("opacity") === "0") {
subnav.css("display", "none");
}
}, 300);
}
};
I tried to replace "hoverIntent" by "click" but it doesn't work, what can I do?
What's happening when someone currently hovers, it does one thing while hovering and when they leave it has to d a sort of cleanup which are the two functions within hoverintent, namely over and out so the code would need to be split into two event listeners one for click of the element and one for blur
I have chained the two listeners to the inital selector so it should all work.
var nav = {
init: function() {
// Add parent class to items with sub-menus
jQuery("ul.sub-menu").parent().addClass('parent');
var menuTop = 40;
var menuTopReset = 80;
// Enable click dropdowns for window size above tablet width
jQuery("nav").find(".menu li.parent").on('click', function (event) {
if($(event.target).parent().hasClass('menu-item-has-children')){
event.preventDefault();
};
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
// Setup menuLeft variable, with main menu value
var subMenuWidth = jQuery(this).find('ul.sub-menu').first().outerWidth(true);
var mainMenuItemWidth = jQuery(this).outerWidth(true);
var menuLeft = '-' + (Math.round(subMenuWidth / 2) - Math.round(mainMenuItemWidth / 2)) + 'px';
var menuContainer = jQuery(this).parent().parent();
// Check if this is the top bar menu
if (menuContainer.hasClass("top-menu")) {
if (menuContainer.parent().parent().parent().hasClass("top-bar-menu-right")) {
menuLeft = "";
} else {
menuLeft = "-1px";
}
menuTop = 30;
menuTopReset = 40;
} else if (menuContainer.hasClass("header-menu")) {
menuLeft = "-1px";
menuTop = 28;
menuTopReset = 40;
} else if (menuContainer.hasClass("mini-menu") || menuContainer.parent().hasClass("mini-menu")) {
menuTop = 40;
menuTopReset = 58;
} else {
menuTop = 44;
menuTopReset = 64;
}
// Check if second level dropdown
if (jQuery(this).find('ul.sub-menu').first().parent().parent().hasClass("sub-menu")) {
menuLeft = jQuery(this).find('ul.sub-menu').first().parent().parent().outerWidth(true) - 2;
}
jQuery(this).find('ul.sub-menu').first().addClass('show-dropdown').css('top', menuTop);
}
}).on('mouseleave',function () {
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
jQuery(this).find('ul.sub-menu').first().removeClass('show-dropdown').css('top', menuTopReset);
}
});
// Toggle Mobile Nav show/hide
jQuery('a.show-main-nav').on('click', function(e) {
e.preventDefault();
if (jQuery('#main-navigation').is(':visible')) {
jQuery('.header-overlay .header-wrap').css('position', '');
} else {
jQuery('.header-overlay .header-wrap').css('position', 'relative');
}
jQuery('#main-navigation').toggle();
});
jQuery(window).smartresize(function(){
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
var menus = jQuery('nav').find('ul.menu');
menus.each(function() {
jQuery(this).css("display", "");
});
}
});
// Set current language to top bar item
var currentLanguage = jQuery('li.aux-languages').find('.current-language span').text();
if (currentLanguage !== "") {
jQuery('li.aux-languages > a').text(currentLanguage);
}
},
hideNav: function(subnav) {
setTimeout(function() {
if (subnav.css("opacity") === "0") {
subnav.css("display", "none");
}
}, 300);
}
};
That seems overly complicated. Do you have a link to the live version?
Usually, when doing a click-to-see submenu with a clickable parent, I set a variable to see whether the menu is open, if not dont go to link. if so, go to link.
An example: http://codepen.io/jhealey5/pen/iLgom
var $handle = $('.sub-menu').prev();
var opened = 0;
$handle.on('click', function(e){
if (opened) {
window.location.href = $(this).attr('href');
} else {
e.preventDefault();
e.stopPropagation();
$('.sub-menu').slideToggle();
opened = 1;
}
});
$('html').on('click', function(){
if (opened) {
$('.sub-menu').slideToggle();
opened = 0;
}
});
Depending on that menu of yours, you could use something similar. But it's using a lot of code for a menu.

Categories

Resources