Jquery Slide Menu with Double Tap to go - javascript

I was using a jquery slide menu on my website just like:
http://www.dynamicdrive.com/style/csslibrary/item/jquery_multi_level_css_menu_2/
then when I started to renew my site I saw this:
http://osvaldas.info/drop-down-navigation-responsive-and-touch-friendly/tag/touch
which is nice on mobile devices but only has only one level depth.
I tried to merge them together but I couldn't. Is it possible to do it? If so how?
//jqueryslidemenu.js
//Specify full URL to down and right arrow images (23 is padding-right to add to top level LIswith drop downs):
var arrowimages={down:['downarrowclass', 'down.gif', 23], right:['rightarrowclass', 'right.gif']}
var jqueryslidemenu={
animateduration: { over: 200, out: 100 }, //duration of slide in/ out animation, in milliseconds
buildmenu:function(menuid, arrowsvar){
jQuery(document).ready(function($){
var $mainmenu=$("#"+menuid+">ul")
var $headers=$mainmenu.find("ul").parent()
$headers.each(function(i){
var $curobj=$(this)
var $subul=$(this).find('ul:eq(0)')
this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
this.istopheader=$curobj.parents("ul").length==1? true : false
$subul.css({top:this.istopheader? this._dimensions.h+"px" : 0})
$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: arrowsvar.down[2]} : {}).append(
'<img src="'+ (this.istopheader? arrowsvar.down[1] : arrowsvar.right[1])
+'" class="' + (this.istopheader? arrowsvar.down[0] : arrowsvar.right[0])
+ '" style="border:0;" />'
)
$curobj.hover(
function(e){
var $targetul=$(this).children("ul:eq(0)")
this._offsets={left:$(this).offset().left, top:$(this).offset().top}
var menuleft=this.istopheader? 0 : this._dimensions.w
menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft
if ($targetul.queue().length<=1) //if 1 or less queued animations
$targetul.css({left:menuleft+"px", width:this._dimensions.subulw+'px'}).slideDown(jqueryslidemenu.animateduration.over)
},
function(e){
var $targetul=$(this).children("ul:eq(0)")
$targetul.slideUp(jqueryslidemenu.animateduration.out)
}
) //end hover
$curobj.click(function(){
$(this).children("ul:eq(0)").hide()
})
}) //end $headers.each()
$mainmenu.find("ul").css({display:'none', visibility:'visible'})
}) //end document.ready
}
}
//build menu with ID="myslidemenu" on page:
jqueryslidemenu.buildmenu("myslidemenu", arrowimages)
I want to merge this code with the one below. I tried but I couldn't make it. Where should I add it?
// Doubletaptogo.js
;(function ($, window, document, undefined) {
$.fn.doubleTapToGo = function (params) {
if (!('ontouchstart' in window) &&
!navigator.msMaxTouchPoints &&
!navigator.userAgent.toLowerCase().match(/windows phone os 7/i)) return false;
this.each(function () {
var curItem = false;
$(this).on('click', function (e) {
var item = $(this);
if (item[0] != curItem[0]) {
e.preventDefault();
curItem = item;
}
});
$(document).on('click touchstart MSPointerDown', function (e) {
var resetItem = true,
parents = $(e.target).parents();
for (var i = 0; i < parents.length; i++)
if (parents[i] == curItem[0])
resetItem = false;
if (resetItem)
curItem = false;
});
});
return this;
};
})(jQuery, window, document);
$(function () {
$('#myslidemenu li:has(ul)').doubleTapToGo();
});
Thanks

What i would do is register a timer on your first click, save that variable within your plugin scope, and access it again to determine if enough time has passed to determine it as a double click. I think double click by standard is 750ms.
Or I believe jQuery has a built in .dblclick() (which may only work on desktop using click events).
I found this snippet of code online:
(function($) {
$.fn.doubleTap = function(doubleTapCallback) {
return this.each(function(){
var elm = this;
var lastTap = 0;
$(elm).bind('vmousedown', function (e) {
var now = (new Date()).valueOf();
var diff = (now - lastTap);
lastTap = now ;
if (diff < 250) {
if($.isFunction( doubleTapCallback ))
{
doubleTapCallback.call(elm);
}
}
});
});
}
})(jQuery);

Related

Magnific Popup and Isotope

I'm using an existing code, written not by me and I have a very limited experience in Java. The code creates a filtered gallery with 15 pics per page using isotope.pkgd.min. Each pic can be opened in a popup, magnific popup.
The problem: I have a filter item e.g. nature with 30-40 pics. The code creates two pages with 15 items per page. However also the popup shows only 15 items and not 30-40. What do I need to do, in order to show 30-40 items in popup but keep 15 items per page in the gallery? Many thanks in advance for your help
$(document).ready(function () {
/*************** Gallery ******************/
var itemSelector = ".tm-gallery-item";
var responsiveIsotope = [ [480, 4], [720, 6] ];
var itemsPerPageDefault = 15;
var itemsPerPage = defineItemsPerPage();
var currentNumberPages = 1;
var currentPage = 1;
var currentFilter = '*';
var filterValue = "";
var pageAttribute = 'data-page';
var pagerClass = 'isotope-pager';
var $container = $('.tm-gallery-container').isotope({
itemSelector: itemSelector
});
function adjustGalleryLayout(currentPopup) {
if(currentPopup == 'gallery') {
// layout Isotope after each image loads
$container.imagesLoaded().progress( function() {
$container.isotope('layout');
});
}
}
/************** Popup *****************/
$('#inline-popups').magnificPopup({
delegate: 'a',
removalDelay: 500, //delay removal by X to allow out-animation
callbacks: {
beforeOpen: function() {
this.st.mainClass = this.st.el.attr('data-effect');
},
open: function() {
adjustGalleryLayout($.magnificPopup.instance.content.attr('id'));
}
},
midClick: true, // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
showCloseBtn: false
});
$('.tm-close-popup').on( "click", function() {
$.magnificPopup.close();
});
var popupInstance = $.magnificPopup.instance;
$('.tm-btn-next').on("click", function(e) {
popupInstance.next();
adjustGalleryLayout(popupInstance.content.attr('id'));
});
$('.tm-btn-contact').on("click", function(e) {
popupInstance.goTo(4);
})
// update items based on current filters
function changeFilter(selector) { $container.isotope({ filter: selector });
$(selector).magnificPopup({
delegate: 'a',
type:'image',
gallery:{
enabled:true
}
})
}
// grab all checked filters and goto page on fresh isotope output
function goToPage(n) {
currentPage = n;
var selector = itemSelector;
var exclusives = [];
if(currentFilter != '*') {
exclusives.push(selector + '.' + currentFilter);
}
// smash all values back together for 'and' filtering
filterValue = exclusives.length ? exclusives.join('') : '*';
a=exclusives;
// add page number to the string of filters
var wordPage = currentPage.toString();
filterValue += ('.'+wordPage);
changeFilter(filterValue);
}
// determine page breaks based on window width and preset values
function defineItemsPerPage() {
var pages = itemsPerPageDefault;
for( var i = 0; i < responsiveIsotope.length; i++ ) {
if( $(window).width() <= responsiveIsotope[i][0] ) {
pages = responsiveIsotope[i][1];
break;
}
}
return pages;
}
function setPagination() {
var SettingsPagesOnItems = function(){
var itemsLength = $container.children(itemSelector).length;
var pages = Math.ceil(itemsLength / itemsPerPage);
var item = 1;
var page = 1;
var selector = itemSelector;
var exclusives = [];
if(currentFilter != '*') {
exclusives.push(selector + '.' + currentFilter);
}
// smash all values back together for 'and' filtering
filterValue = exclusives.length ? exclusives.join('') : '*';
// find each child element with current filter values
$container.children(filterValue).each(function(){
// increment page if a new one is needed
if( item > itemsPerPage ) {
page++;
item = 1;
}
// add page number to element as a class
wordPage = page.toString();
var classes = $(this).attr('class').split(' ');
var lastClass = classes[classes.length-1];
// last class shorter than 4 will be a page number, if so, grab and replace
if(lastClass.length < 4){
$(this).removeClass();
classes.pop();
classes.push(wordPage);
classes = classes.join(' ');
$(this).addClass(classes);
} else {
// if there was no page number, add it
$(this).addClass(wordPage);
}
item++;
});
currentNumberPages = page;
}();
// create page number navigation
var CreatePagers = function() {
var $isotopePager = ( $('.'+pagerClass).length == 0 ) ? $('<div class="'+pagerClass+' tm-paging"></div>') : $('.'+pagerClass);
$isotopePager.html('');
if(currentNumberPages > 1){
for( var i = 0; i < currentNumberPages; i++ ) {
var $pager = '';
if(currentPage == i+1) {
$pager = $('');
} else {
$pager = $('');
}
$pager.html(i+1);
$pager.click(function(){
$('.tm-paging-link').removeClass('active');
$(this).addClass('active');
var page = $(this).eq(0).attr(pageAttribute);
goToPage(page);
});
$pager.appendTo($isotopePager);
}
}
$container.after($isotopePager);
}();
}
setPagination();
goToPage(1);
//event handlers
$('.tm-gallery-link').click(function(e) {
var filter = $(this).data('filter');
currentFilter = filter;
setPagination();
goToPage(1);
$('.tm-gallery-link').removeClass('active');
$(e.target).addClass('active');
})
//Handle window resize
$(window).resize(function(){
itemsPerPage = defineItemsPerPage();
setPagination();
goToPage(1);
});
});

jQuery extending my vertical tabs

Im new to jQuery and wanting to make this a little cleaner and also add functionality but not sure on how rto do it so hoping someone could give me a hand.
tabs (working) so far
$(".tabs-menu a").click(function(event) {
event.preventDefault();
$(this).parent().addClass("active");
$(this).parent().siblings().removeClass("active");
var tab = $(this).attr("href");
$(".tab-content").not(tab).css("display", "none");
$(tab).show();
});
At the moment only works on click event but want to add something so i can add auto changing of tabs like using
hokTabs.pause();
etc.. this is mainly for when you hover an iutem it will pause and start again when you hover of button.
Anyone have any ideas?
// New Veritcal Tabs JS
(function (hokTabs, $) {
var internal = '5000'; // Internal
// start auto tabs
hokTabs.start = function () {
console.log('started');
}
// start auto tabs
hokTabs.stop = function () {
console.log('started');
}
// start auto tabs
hokTabs.pause = function () {
console.log('started');
}
}(window.hokTabs, jQuery));
These are simple start and stop functions, you just simply link them to hover events:
$(document).ready(function($) {
var activateTab = function(index) {
var tab = $(".tabs-menu li:eq(" + index + ")"),
tabContent = $(".tab div:eq(" + index + ")");
tab.addClass("current");
tab.siblings().removeClass("current");
tabContent.siblings().css("display", "none");
tabContent.show();
}
var automation = {
start: function() {
this.current = setInterval(function() {
var currentIndex = $(".tabs-menu li.current").index(),
max = $(".tabs-menu li.current").parent().children().length;
activateTab(currentIndex + 1 < max ? currentIndex + 1 : 0);
}, 2000);
},
stop: function() {
if (this.current) {
clearInterval(this.current);
}
}
}
$(".tabs-menu a").click(function(event) {
event.preventDefault();
activateTab($(event.currentTarget).parent().index());
});
automation.start();
});
JS Fiddle: https://jsfiddle.net/5zmcn3h2/10/

how to use/call this function in javascript/jquery?

im very new to jquery/javascript. So here goes, I found this js code for swipedown and swipeup. But don't know how to use it or call it.
The js code:
(function() {
// initializes touch and scroll events
var supportTouch = $.support.touch,
scrollEvent = "touchmove scroll",
touchStartEvent = supportTouch ? "touchstart" : "mousedown",
touchStopEvent = supportTouch ? "touchend" : "mouseup",
touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
// handles swipeup and swipedown
$.event.special.swipeupdown = {
setup: function() {
var thisObject = this;
var $this = $(thisObject);
$this.bind(touchStartEvent, function(event) {
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] :
event,
start = {
time: (new Date).getTime(),
coords: [ data.pageX, data.pageY ],
origin: $(event.target)
},
stop;
function moveHandler(event) {
if (!start) {
return;
}
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] :
event;
stop = {
time: (new Date).getTime(),
coords: [ data.pageX, data.pageY ]
};
// prevent scrolling
if (Math.abs(start.coords[1] - stop.coords[1]) > 10) {
event.preventDefault();
}
}
$this
.bind(touchMoveEvent, moveHandler)
.one(touchStopEvent, function(event) {
$this.unbind(touchMoveEvent, moveHandler);
if (start && stop) {
if (stop.time - start.time < 1000 &&
Math.abs(start.coords[1] - stop.coords[1]) > 30 &&
Math.abs(start.coords[0] - stop.coords[0]) < 75) {
start.origin
.trigger("swipeupdown")
.trigger(start.coords[1] > stop.coords[1] ? "swipeup" : "swipedown");
}
}
start = stop = undefined;
});
});
}
};
//Adds the events to the jQuery events special collection
$.each({
swipedown: "swipeupdown",
swipeup: "swipeupdown"
}, function(event, sourceEvent){
$.event.special[event] = {
setup: function(){
$(this).bind(sourceEvent, $.noop);
}
};
});
})();
this is the anchor element that I want to trigger using the above code
tried call the function like this:
$('#swipedown').live('swipedown', function(event, data){
alert('swipes')
});
but it didn't prompt me the alert. >.<.
Any help will be much appreciated.
The last () are calling the funcion after it's created. The funcion adds a new possibility to jquery. So you can probably call it doing:
$('#swipedown').bind('swipedown', function(e){
alert('test');
});
Your code will be added (as documented) to the jQuery events special collection this means that you could call swipeup or swipedown as any other jQuery event.
example:
$("div p").live('swipedown',function() {
alert("swiped down");
});
That will be triggered on a swipedown action happening to a p element like:
<body>
<div>
<h1>hello world</h1>
<p>pull me down</p>
</div>
</body>

How to increase performance of this js script (function calls exponentially increasing)?

Any general tips how to increase a longish js code like this? It works great but sometimes it gets a little sluggish and all the drag/drop and ajax features slow down.
I know this code is a little longer so I am not looking for specific suggestions. Just your first thoughts after taking a quick glance at this code.
EDIT:
I have found a pretty scary thing. The calls to dragDrop() are exponentially increasing in the $('.folderListOnclick').click event. After each click dragDrop() is called 1 time, 2 times, 4 times, 8 times. That's what's slowing it down.
But I don't understand why it is happening.
<script type="text/javascript">
//<!--
$(document).ready(function() {
function in_array (needle, haystack, argStrict) {
var key = '', strict = !!argStrict;
if (strict) {
for (key in haystack) {
if (haystack[key] === needle) {
return true; }
}
} else {
for (key in haystack) {
if (haystack[key] == needle) {
return true;
}
}
}
return false;
}
var openedFolders = new Array();
var start = 0;
var stop = 0;
$('.drag').each(function() {
var draggables = $(this).parents('table').find('.drag');
var $next = draggables.filter(':gt(' + draggables.index(this) + ')').first();
var width = $(this).css('width');
var nextWidth = $next.css('width');
if (nextWidth > width /*&& 30 == parseInt(width)*/) {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
if (in_array($(this).attr('rel'), openedFolders)) {
$(this).addClass('ordinaryFolderOpened');
} else {
$(this).addClass('ordinaryFolderClosed');
}
}
if (in_array($(this).attr('rel'), openedFolders)) {
start = 1;
}
if (1 == start && stop < 2) {
if (30 == parseInt(width)) {
stop++;
}
} else {
start = 0;
stop = 0;
if (parseInt(width) > 30) {
$(this).parent().parent().hide();
}
}
});
function dragDrop()
{
$('.folders .trow1').hover(
function () {
if ($(this).css('backgroundColor') != 'rgb(52, 108, 182)' && $(this).css('backgroundColor') != '#346cb6') {
$(this).css('background', "#C2E3EF");
}
},
function () {
if ($(this).css('backgroundColor') != 'rgb(52, 108, 182)' && $(this).css('backgroundColor') != '#346cb6') {
$(this).css('background', 'transparent');
}
}
);
$('.drag').click(function() {
if ($(this).hasClass('noclick')) {
$(this).removeClass('noclick');
} else {
var draggables = $(this).parents('table').find('.drag');
var $next = draggables.filter(':gt(' + draggables.index(this) + ')').first();
var width = $(this).css('width');
var nextWidth = $next.css('width');
if (nextWidth > width /*&& 30 == parseInt(width)*/) {
var isVisible = $next.is(':visible');
if (isVisible) {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
$(this).addClass('ordinaryFolderClosed');
} else {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
$(this).addClass('ordinaryFolderOpened');
}
clickedId = $(this).attr('rel');
clickedId = clickedId.split(',');
clickedType = clickedId[1];
clickedId = clickedId[0];
// $.ajax({
// type: 'POST',
// url: 'body/obsah/mediaManager/setOpenedFolder.php',
// data: 'id='+clickedId+'&type='+clickedType,
// success: function(msg){
// //alert(msg);
// }
// });
var start = 0;
var stop = 0;
var i = 0;
// close folder
if (isVisible) {
$('.drag').each(function() {
if (0 == start) {
iteratedId = $(this).attr('rel');
iteratedId = iteratedId.split(',');
iteratedId = iteratedId[0];
if (iteratedId == clickedId) {
start = 1;
}
}
if (1 == start && stop < 2) {
if ($(this).css('width') > width) {
$(this).parent().parent().hide();
if ($(this).hasClass('ordinaryFolderClosed') || $(this).hasClass('ordinaryFolderOpened')) {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
$(this).addClass('ordinaryFolderClosed');
}
} else {
stop++;
}
}
i++;
});
}
// open folder
else {
$('.drag').each(function() {
if (0 == start) {
iteratedId = $(this).attr('rel');
iteratedId = iteratedId.split(',');
iteratedId = iteratedId[0];
if (iteratedId == clickedId) {
start = 1;
}
}
if (1 == start && stop < 2) {
if (parseInt($(this).css('width')) == parseInt(width)+5) {
$(this).parent().parent().show();
}
if (parseInt($(this).css('width')) == parseInt(width)) {
stop++;
}
}
i++;
});
}
}
}
});
var dragId = 0;
var dragType = 0;
var dropId = 0;
var dropType = 0;
var isFile = false;
$('.drag').draggable({
revert: true,
cursorAt: {top: 0, left: 0},
drag: function() {
if ($(this).attr('rel') !== undefined) {
dragId = $(this).attr('rel');
dragId = dragId.split(',');
dragType = dragId[1];
dragId = dragId[0];
}
isFile = false;
},
start: function(event, ui) {
$(this).addClass('noclick');
}
});
$('.drag2').draggable({
revert: true,
cursorAt: {top: 0, left: 0},
drag: function() {
if ($(this).attr('rel') !== undefined) {
dragId = $(this).attr('rel');
dragId = dragId.split(',');
dragType = dragId[1];
dragId = dragId[0];
}
isFile = true;
}
});
$('.drop').droppable({
tolerance: 'pointer',
drop: function() {
if ($(this).attr('rel') !== undefined) {
dropId = $(this).attr('rel');
dropId = dropId.split(',');
dropType = dropId[1];
dropId = dropId[0];
if (dropId != dragId) {
if (false == isFile) {
$.ajax({
type: 'POST',
url: 'body/obsah/mediaManager/folder_move.php',
data: 'nid='+dragId+'&pid='+dropId+'&ft='+dropType,
success: function(msg){
ajaxElementCall('left1', 'body/obsah/mediaManager/folder_list.php?type=1', 'right1', 'body/obsah/mediaManager/file_list.php?type=1&browse=0&assignType=0&CKEditorFuncNum=0&idFolder=0');
dragDrop();
}
});
} else if (true == isFile) {
$.ajax({
type: 'POST',
url: 'body/obsah/mediaManager/file_move.php',
data: 'fid='+dragId+'&did='+dropId+'&ft='+dropType,
success: function(msg){
ajaxElementCall('right1', 'body/obsah/mediaManager/file_list.php?type=1&browse=0&assignType=0&CKEditorFuncNum=0&idFolder=0&reloadTree=0');
dragDrop();
}
});
}
}
}
}
});
}
dragDrop();
$('.folderListOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel')+'&browse=0&assignType=0&CKEditorFuncNum=0&reloadTree=0';
ajaxElementCall('right1', 'body/obsah/mediaManager/file_list.php?type=1&'+append);
dragDrop();
$('.trow1').css('background', 'transparent');
$('.trow1').css('color', '#3e4245');
$(this).parent().css('background', "#346cb6 url('img/menuButtonOver.png') left top repeat-x");
$(this).parent().css('color', 'white');
});
$('.folderEditOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel')+'&browse=0&assignType=0&CKEditorFuncNum=0';
showModal('modal_div', 'Editácia adresára');
ajaxElementCall('modal_div', 'body/obsah/mediaManager/folder_edit.php?kam=edit1&'+append);
});
$('.folderDeleteOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel')+'&browse=0&assignType=0&CKEditorFuncNum=0';
showModal('modal_div', 'Vymazanie adresára');
ajaxElementCall('modal_div', 'body/obsah/mediaManager/folder_delete.php?kam=del1&'+append);
});
$('.addNewFolder').click(function() {
showModal('modal_div', 'Nový adresár');
var id = '0';
$('.folders .trow1').each(function() {
if ($(this).css('backgroundColor') == 'rgb(52, 108, 182)' || $(this).css('backgroundColor') == '#346cb6') {
id = $(this).attr('rel');
id = id.split(',');
id = id[0];
}
});
ajaxElementCall('modal_div', '/body/obsah/mediaManager/folder_add.php?type=1&kam=new1&idFolder='+id+'&browse=0&assignType=0&CKEditorFuncNum=0');
});
}); //-->
</script>
Well you have not posted any of your HTML markup, and you have not posted the details of what the "ajaxElementCall" function does. Therefore it's hard to say exactly how you should fix the problem. It is true however that on every "drop" event, you end up calling the "dragDrop()" setup function again. You say that "ajaxElementCall" reloads some portion of the page, but your "dragDrop()" code always installs new event handlers on all ".drag" and ".drop" elements on the page. If "ajaxElementCall" only updates part of the page, then all the unchanged ".drag" and ".drop" elements will get additional event handlers piled on.
When you call .click() or .hover() for some selector, jQuery adds the event handler you supply to the set of handlers already registered. Thus, because you register new event handlers every time "dragDrop()" is called, you'll get more and more piled up. When an event happens, all of those handlers will be run.
Probably what you need to do is change "dragDrop()" so that you can tell it to only operate on a particular fraction of the page. Either that, or else when it runs it should "mark" each element it affects and then check for that mark before applying new event handlers. That way it will only affect newly-loaded code. (It would be more efficient to narrow down the search, however; the expression $('.drag') may have to look through every DOM element on the page, so it would be preferable to use something more precise anyway.)
For one, all the $(this) should be changed to use a variable.
var me = $(this);
me.XXX
$(this) is a method call and its unnessesary to call it over and over again on the same object.
This needs to be done on a per block basis as this will be differet objects in every block ;)
Lookup operations like $(this) are pretty expensive. You'd better store and address object references instead; it helped me a lot in similar circumstances.
It won't make it that much faster, but this will speed it up a few milliseconds:
You should reuse a jquery instance instead of generating a new one (this costs some time).
Example: instead of
$(this).parent().css('background', "#346cb6 url('img/menuButtonOver.png') left top repeat-x");
$(this).parent().css('color', 'white');
use
var this_parent = $(this).parent();
this_parent.css('background', "#346cb6 url('img/menuButtonOver.png') left top repeat-x");
this_parent.css('color', 'white');
One thing that can significantly optimize the above code is replacing the in_array function and the openedFolders array a JS object that functions as a dictionary and is much more efficient.
Decleration:
openedFolders={};
Add a new folder to the opened folders object:
openedFolders[folderName]=valueRelatedToTheFolderIfYouHaveOneOrWhatEver; // :)
Search for an opened folder:
if(openedFolders.hasOwnProperty(folderName)){/*folderName is open*/}

Javascript causing memory leak [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I can't for the life of me figure out why loading this page...
http://polyphonic.hannahkingdev.com/work/cowboys-angels or any other video page sometimes causes the browser to hang and then prompts me to stop the script that is causing the browser to slowdown.
If the video is left to run, by the time you go to close the page, the browser is pretty unresponsive. This is the same in FFox, Safari & Chrome.
Any help finding the memory leak would be most appreciated. I am completely stumped on this one.
Many thanks
var $ = jQuery.noConflict();
$(document).ready(initPage);
// -- Init -- //
function initPage() {
resizeWork();
//hoverWorkImg();
};
// -- Pageload -- //
$(document).ready(function() {
$(".animsition").animsition({
inClass: 'overlay-slide-in-left',
outClass: 'overlay-slide-out-left',
inDuration: 1500,
outDuration: 800,
linkElement: 'a:not([target="_blank"]):not([href^=#]):not([href^=mailto]:not([href^=tel])',
loading: true,
loadingParentElement: 'body', //animsition wrapper element
loadingClass: 'animsition-loading',
loadingInner: '', // e.g '<img src="loading.svg" />'
timeout: false,
timeoutCountdown: 5000,
onLoadEvent: true,
browser: [ 'animation-duration', '-webkit-animation-duration'],
overlay : true,
overlayClass : 'animsition-overlay-slide',
overlayParentElement : 'body',
transition: function(url){ window.location.href = url; }
});
});
// -- Navigation -- //
if (document.getElementById('menu-button') !=null) {
var button = document.getElementById('menu-button');
var menu = document.getElementById('menu-main-navigation');
var menuPos = window.innerHeight;
var menuFixed = false;
button.addEventListener('click', function(ev){
ev.preventDefault();
menu.classList.toggle('navigation--isOpen');
button.classList.toggle('navigation-button--isOpen');
})
updateMenuPosition();
window.addEventListener('resize', updateMenuPosition);
// -- Highlight nav -- /
var $navigationLinks = $('#menu-main-navigation > li > a');
var $sections = $($("section").get().reverse());
var sectionIdTonavigationLink = {};
$sections.each(function() {
var id = $(this).attr('id');
sectionIdTonavigationLink[id] = $('#menu-main-navigation > li > a[href="#' + id + '"]');
});
function throttle(fn, interval) {
var lastCall, timeoutId;
return function () {
var now = new Date().getTime();
if (lastCall && now < (lastCall + interval) ) {
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
lastCall = now;
fn.call();
}, interval - (now - lastCall) );
} else {
lastCall = now;
fn.call();
}
};
}
function highlightNavigation() {
var scrollPosition = $(window).scrollTop();
$sections.each(function() {
var currentSection = $(this);
var sectionTop = currentSection.offset().top;
if (scrollPosition >= sectionTop) {
var id = currentSection.attr('id');
var $navigationLink = sectionIdTonavigationLink[id];
if (!$navigationLink.hasClass('active')) {
$navigationLinks.removeClass('active');
$navigationLink.addClass('active');
}
return false;
}
});
}
$(window).scroll( throttle(highlightNavigation,100) );
}
function updateMenuPosition(){
if(menuFixed){
menu.classList.remove('navigation--white');
menuPos = menu.offsetTop;
menu.classList.add('navigation--white');
} else {
menuPos = menu.offsetTop;
}
updateMenuAttachment();
}
updateMenuAttachment();
window.addEventListener('scroll', updateMenuAttachment);
function updateMenuAttachment(){
var scrollPos = document.documentElement.scrollTop || document.body.scrollTop;
if(!menuFixed && scrollPos >= window.innerHeight - 200){
menu.classList.add('navigation--white');
menuFixed = true;
} else if(menuFixed && scrollPos < window.innerHeight - 200){
menu.classList.remove('navigation--white');
menuFixed = false;
}
}
// -- Smooth scroll to anchor -- /
$('a[href*="#"]')
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (this.hash=="#work") {;
var offsetT = (target.offset().top)-90;
} else {
var offsetT = (target.offset().top);
}
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: offsetT
}, 1000, function() {
});
}
}
});
// -- Back to top -- /
jQuery(document).ready(function($){
var offset = 300,
offset_opacity = 1200,
scroll_top_duration = 700,
$back_to_top = $('.cd-top');
$(window).scroll(function(){
( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
if( $(this).scrollTop() > offset_opacity ) {
$back_to_top.addClass('cd-fade-out');
}
});
$back_to_top.on('click', function(event){
event.preventDefault();
$('body,html').animate({
scrollTop: 0 ,
}, scroll_top_duration
);
});
});
// -- Animate -- /
new WOW().init();
// -- Inline all SVGs -- /
jQuery('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Check if the viewport is set, if the viewport is not set the SVG wont't scale.
if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
$svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))
}
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
// -- work grid -- /
function resizeWork() {
var div = $('.work article');
div.css('height', div.width() / 1.9);
}
function hoverWorkImg() {
$('article a').on('mouseenter', function () {
$(this).find('.imagehover:hidden').fadeIn(700);
$(this).find('.second:hidden').fadeIn(700);
$(this).find('.first:visible').fadeOut(700);
})
$('article a').on('mouseleave', function () {
$(this).find('.imagehover:visible').fadeOut(700);
$(this).find('.second:visible').fadeOut(700);
$(this).find('.first:hidden').fadeIn(700);
})
}
// -- Video Page -- /
function playVideoInPage() {
showModal(false);
initPlayer();
startPlay();
}
var $video,
$playPauseButton,
$muteButton,
$seekBar,
isMouseMove=false,
$timing;
function showModal(html) {
if (html !== false) {
$('.work-video').html(html).fadeIn();
}
else {
$('.work-video').fadeIn();
}
hidePlayerControls();
}
function initPlayer() {
$('#video').css('height', $(window).height());
$video = $('.video-container'),
$playPauseButton = $('#play-pause'),
$muteButton = $('#mute'),
$seekBar = $('#seek-bar'),
$timing = $('.timing');
/*setTimeout('showPlayerControls()', 1500);*/
$playPauseButton.on('click', function () {
if ($video.get()[0].paused == true) {
$video.get()[0].play();
$playPauseButton.removeClass('paused');
}
else {
$video.get()[0].pause();
$playPauseButton.addClass('paused');
$timing.stop(true, true);
}
})
$muteButton.on('click', function () {
if ($video.get()[0].muted == false) {
$video.get()[0].muted = true;
$muteButton.addClass('muted');
}
else {
$video.get()[0].muted = false;
$muteButton.removeClass('muted');
}
})
$seekBar.on("click", function (e) {
var x = e.pageX - $(this).offset().left,
widthForOnePercent = $seekBar.width() / 100,
progress = x / widthForOnePercent,
goToTime = progress * ($video.get()[0].duration / 100);
goToPercent(progress)
$video.get()[0].currentTime = goToTime;
});
$video.get()[0].addEventListener("timeupdate", function () {
var value = (100 / $video.get()[0].duration) * $video.get()[0].currentTime;
goToPercent(value)
});
}
function startPlay() {
$playPauseButton.click();
}
function goToPercent(value) {
$timing.css('width', value + '%');
}
function showPlayerControls() {
$('.controls').fadeIn();
isMouseMove=true;
}
function hidePlayerControls() {
$('.controls').fadeOut();
}
function hidePlayerControls() {
setInterval(function() {
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
$(document).mousemove(function (event) {
isMouseMove=true;
showPlayerControls();
});
}
The most likely cause is this code here:
function hidePlayerControls() {
setInterval(function() {
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
so every 4 seconds you start a new interval (interval = repeat until cancelled).
In the first case, you might like to change this to setTimeout
function hidePlayerControls() {
setTimeout(function() {
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
In the second, you could change this to cancel the previous timeout when the mouse moves - this is termed debouncing - though usually with a shorter interval, the principle is the same.
As a general debugging tip, liberally add console.log statements and watch your browser console (there are other ways, this is a basic debugging first-step), eg:
function hidePlayerControls() {
console.log("hidePlayerControls() called");
setInterval(function() {
console.log("hidePlayerControls - interval triggered", isMouseMove);
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
to see just how many times this gets called

Categories