JavaScript function is preventing link working - javascript

This javascript function is used to animate a number of selection boxes, however, I want to be able to use these selection boxes as A HREF links but i believe that something in this javascript is preventing it from acting as a href link.
Please could someone help point me in the right direction
Any help much appreciated thank you
(function() {
var $container = $('#portfolio-items');
if( $container.length ) {
var $itemsFilter = $('#portfolio-items-filter'),
mouseOver;
// Copy categories to item classes
$('article', $container).each(function(i) {
var $this = $(this);
$this.addClass( $this.attr('data-categories') );
});
// Run Isotope when all images are fully loaded
$(window).on('load', function() {
$container.isotope({
itemSelector : 'article',
layoutMode : 'fitRows'
});
});
// Filter projects
$itemsFilter.on('click', 'a', function(e) {
var $this = $(this),
currentOption = $this.attr('data-categories');
$itemsFilter.find('a').removeClass('active');
$this.addClass('active');
if( currentOption ) {
if( currentOption !== '*' ) currentOption = currentOption.replace(currentOption, '.' + currentOption)
$container.isotope({ filter : currentOption });
}
e.preventDefault();
});
$itemsFilter.find('a').first().addClass('active');
$itemsFilter.find('a').not('.active').hide();
// On mouseover (hover)
$itemsFilter.on('mouseenter', function() {
var $this = $(this);
clearTimeout( mouseOver );
// Wait 100ms before animating to prevent unnecessary flickering
mouseOver = setTimeout( function() {
if( $(window).width() >= 960 )
$this.find('li a').stop(true, true).slideHorzShow(300);
}, 100);
}).on('mouseleave', function() {
clearTimeout( mouseOver );
if( $(window).width() >= 960 )
$(this).find('li a').not('.active').stop(true, true).slideHorzHide(150);
});
}
})();

Just remove:
e.preventDefault();

Related

Vertical Scrolling Issues on Mobile

So I'm having scrolling issues on my site when viewing on mobile browsers. For some reason, scrolling is sometimes stopped or frozen and there is a weird vertical scrolling bar line that appears randomly in the middle of the browser. I have no idea what this could be, I figure it's a js issue between the menu and the project container but not sure if it may be css overflow issue. The link is johnavent.net/projects if you want to view yourself.
Here's my JS for the menu:
var isLateralNavAnimating = false;
//open/close lateral navigation
$('.cd-nav-trigger').on('click', function(event){
event.preventDefault();
//stop if nav animation is running
if( !isLateralNavAnimating ) {
if($(this).parents('.csstransitions').length > 0 ) isLateralNavAnimating = true;
$('body').toggleClass('navigation-is-open');
$('.cd-navigation-wrapper').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
//animation is over
isLateralNavAnimating = false;
});
}
});
And here it is for my project contianers:
$('.cd-single-project').bgLoaded({
afterLoaded : function(){
showCaption($('.projects-container li').eq(0));
}
});
$('.cd-single-project').on('click', function(){
var selectedProject = $(this),
toggle = !selectedProject.hasClass('is-full-width');
if(toggle) toggleProject($(this), $('.projects-container'), toggle);
});
$('.projects-container .cd-close').on('click', function(){
toggleProject($('.is-full-width'), $('.projects-container'), false);
});
$('.projects-container .cd-scroll').on('click', function(){
$('.projects-container').animate({'scrollTop':$(window).height()}, 500);
});
$('.projects-container').on('scroll', function(){
window.requestAnimationFrame(changeOpacity);
});
function toggleProject(project, container, bool) {
if(bool) {
container.addClass('project-is-open');
project.addClass('is-full-width').siblings('li').removeClass('is-loaded');
} else {
var mq = window.getComputedStyle(document.querySelector('.projects-container'), '::before').getPropertyValue('content').replace(/"/g, "").replace(/'/g, ""),
delay = ( mq == 'mobile' ) ? 100 : 0;
container.removeClass('project-is-open');
project.animate({opacity: 0}, 800, function(){
project.removeClass('is-loaded');
$('.projects-container').find('.cd-scroll').attr('style', '');
setTimeout(function(){
project.attr('style', '').removeClass('is-full-width').find('.cd-title').attr('style', '');
}, delay);
setTimeout(function(){
showCaption($('.projects-container li').eq(0));
}, 300);
});
}
}
function changeOpacity(){
var newOpacity = 1- ($('.projects-container').scrollTop())/300;
$('.projects-container .cd-scroll').css('opacity', newOpacity);
$('.is-full-width .cd-title').css('opacity', newOpacity);
$('.is-full-width').hide().show(0);
}
function showCaption(project) {
if(project.length > 0 ) {
setTimeout(function(){
project.addClass('is-loaded');
showCaption(project.next());
}, 150);
}
}
});
(function($){
$.fn.bgLoaded = function(custom) {
var self = this;
var defaults = {
afterLoaded : function(){
this.addClass('bg-loaded');
}
};
var settings = $.extend({}, defaults, custom);
self.each(function(){
var $this = $(this),
bgImgs = window.getComputedStyle($this.get(0), '::before').getPropertyValue('content').replace(/'/g, "").replace(/"/g, "").split(', ');
$this.data('loaded-count',0);
$.each( bgImgs, function(key, value){
var img = value.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
$('<img/>').attr('src', img).load(function() {
$(this).remove();
$this.data('loaded-count',$this.data('loaded-count')+1);
if ($this.data('loaded-count') >= bgImgs.length) {
settings.afterLoaded.call($this);
}
});
});
});
};
Will post CSS if the issue does not lie within the JS but everything is what you would think and how it behaves on desktop.

Detecting Animation Elements in View

I am trying to add a class to an element when it is in the viewport. I have achieved this however it causes serious issues to the performance of my site when I scroll.
I currently have this JavaScript:
//Cache reference to window and animation items
var $animation_elements = $('.animation-element');
var $window = $(window);
$window.on('scroll resize', check_if_in_view);
$window.trigger('scroll');
function check_if_in_view() {
var window_height = $window.height();
var window_top_position = $window.scrollTop();
var window_bottom_position = (window_top_position + window_height);
$.each($animation_elements, function() {
var $element = $(this);
var element_height = $element.outerHeight();
var element_top_position = $element.offset().top;
var element_bottom_position = (element_top_position + element_height);
//check to see if this current container is within viewport
if ((element_bottom_position >= window_top_position) &&
(element_top_position <= window_bottom_position)) {
$element.addClass('in-view');
} else {
$element.removeClass('in-view');
}
});
}
So as you can see the check_if_in_view() function seems to be constantly firing as the page is being scrolled and I believe this might be the reason why the performance might be so bad.
Is there a more efficient way of adding a class when scrolling the page that wont cause performance issues on my site?
Use setTimeout to delay calling the function every time a scroll event is fired. In the following code (which I borrowed from Codrops), a flag is set to call the function every 60 milliseconds in the case of continous scrolling.
function Scroller(el) {
this.elements = Array.prototype.slice.call( el );
this._init();
}
Scroller.prototype = {
_init : function() {
//this flag prevents that the function _scrollPage is called
//every time the 'scroll' event is fired
this.didScroll = false;
window.addEventListener( 'scroll', this._scrollHandler.bind(this), false );
},
_scrollHandler : function() {
if( !this.didScroll ) {
this.didScroll = true;
setTimeout( function() { this._scrollPage(); }, 60 );
}
},
_scrollPage : function() {
this.elements.forEach( function( el, i ) {
if( inViewport(el) ) {
classie.add( el, 'i-am-in-the-viewport' );
}
else {
classie.remove( el, 'i-am-in-the-viewport' );
}
});
this.didScroll = false;
}
};
To use it call new Scroller( document.getElementsByClassName('elements-to-watch') );.
Check out the complete code on Codrops to see the implementation of the inViewPort() function. Classie.js is used to handle the assignation of class names.
Don't be afraid to ask for clarification if there's something you don't get!

Saving CSS class on object in localstorage on reload page

What I would like to do, is to have a CSS style saved when a user resreshes the page. This is my jQuery code:
$(function() {
$("#slider").draggable({
axis: 'x',
containment: 'parent',
drag: function(event, ui) {
if (ui.position.left > 230) {
$("#well").fadeOut();
$( "#well" ).addClass( "disappear" );
} else {
// Apparently Safari isn't allowing partial opacity on text with background clip? Not sure.
// $("h2 span").css("opacity", 100 - (ui.position.left / 5))
}
},
stop: function(event, ui) {
if (ui.position.left < 231) {
$(this).animate({
left: 0
})
}
}
});
$('#slider')[0].addEventListener('touchmove', function(event) {
event.preventDefault();
var el = event.target;
var touch = event.touches[0];
curX = touch.pageX - this.offsetLeft - 73;
if(curX <= 0) return;
if(curX > 230){
$('#well').fadeOut();
}
el.style.webkitTransform = 'translateX(' + curX + 'px)';
}, false);
$('#slider')[0].addEventListener('touchend', function(event) {
this.style.webkitTransition = '-webkit-transform 0.3s ease-in';
this.addEventListener( 'webkitTransitionEnd', function( event ) { this.style.webkitTransition = 'none'; }, false );
this.style.webkitTransform = 'translateX(0px)';
}, false);
});
When the class "disappear" is added I would like to keep it added even if the page reloads. I found a useful post here, but since I am a beginner at Javascript, I am not sure how to use it in my case, and I would be really happy if someone could give me a personalized answer.
Thanks in advance!
After $( "#well" ).addClass( "disappear" ); add
localStorage['wellClass'] = 'disappear';
And in the line below $(function() { add
previousWellClass = localStorage['wellClass'];
if (previousWellClass) $('#well').addClass(previousWellClass);
This will do most of the work for you.
var setClass = JSON.parse(localStorage.getItem('setClass')) || {};
$.each(setClass, function () {
$(this.selector).addClass(this.className);
});
var addClassToLocalStorage = function(selector, className) {
setClass[selector + ':' + className] = {
selector: selector,
className: className
};
localStorage.setItem('setClass', JSON.stringify(setClass));
};
var removeClassFromLocalStorage = function(selector, className) {
delete setClass[selector + ':' + className];
localStorage.setItem('setClass', JSON.stringify(setClass));
};
Then you can just do this:
$("#well").fadeOut();
$("#well").addClass("disappear");
addClassToLocalStorage('#well', 'disappear');
// remove it removeClassFromLocalStorage('#well', 'disappear');
FIDDLE
Then you can reuse it if you need to later.

jquery quote rotator quovolver - is there a way to make the quotes random?

I finally got the wonderful "quovolver" to work on my site and my testimonials are all rotating in a lovely way in my sidebar...
I would like however that instead of them running in the same order all the time ( the script for quovolver cycles through them in the order they are in in the html... ) that they be called up randomly by the script...
Is this possible??
Here is the script:
/**
* jQuery Quovolver 2.0.2
* https://github.com/sebnitu/Quovolver
*
* By Sebastian Nitu - Copyright 2012 - All rights reserved
* Author URL: http://sebnitu.com
*/
(function($) {
$.fn.quovolver = function(options) {
// Extend our default options with those provided.
var opts = $.extend({}, $.fn.quovolver.defaults, options);
// This allows for multiple instances of this plugin in the same document
return this.each(function () {
// Save our object
var $this = $(this);
// Build element specific options
// This lets me access options with this syntax: o.optionName
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
// Initial styles and markup
$this.addClass('quovolve')
.css({ 'position' : 'relative' })
.wrap('<div class="quovolve-box"></div>');
if( o.children ) {
var groupMethod = 'find';
} else {
var groupMethod = 'children';
}
// Initialize element specific variables
var $box = $this.parent('.quovolve-box'),
$items = $this[groupMethod](o.children),
$active = 1,
$total = $items.length;
// Hide all except the first
$items.hide().filter(':first').show();
// Call build navigation function
if ( o.navPrev || o.navNext || o.navNum || o.navText ) {
o.navEnabled = true;
var $nav = buildNav();
} else {
o.navEnabled = false;
}
// Call equal heights function
if (o.equalHeight) {
equalHeight( $items );
// Recalculate equal heights on window resize
$(window).resize(function() {
equalHeight( $items );
$this.css('height', $($items[$active -1]).outerHeight() );
});
}
// Auto play interface
if (o.autoPlay) {
var $playID = autoPlay();
if (o.stopOnHover) {
var $playID = stopAutoPlay($playID);
} else if (o.pauseOnHover) {
var $playID = pauseAutoPlay($playID);
}
}
// Go To function
function gotoItem(itemNumber) {
// Check if stuff is already being animated and kill the script if it is
if( $items.is(':animated') || $this.is(':animated') ) return false;
// If the container has been hidden, kill the script
// This prevents the script from bugging out if something hides the revolving
// object from another script (tabs for example)
if( $box.is(':hidden') ) return false;
// Don't let itemNumber go above or below possible options
if ( itemNumber < 1 ) {
itemNumber = $total;
} else if ( itemNumber > $total ) {
itemNumber = 1;
}
// Create the data object to pass to our transition method
var gotoData = {
current : $( $items[$active -1] ), // Save currently active item
upcoming : $( $items[itemNumber - 1] ) // Save upcoming item
}
// Save current and upcoming hights and outer heights
gotoData.currentHeight = getHiddenProperty(gotoData.current);
gotoData.upcomingHeight = getHiddenProperty(gotoData.upcoming);
gotoData.currentOuterHeight = getHiddenProperty(gotoData.current, 'outerHeight');
gotoData.upcomingOuterHeight = getHiddenProperty(gotoData.upcoming, 'outerHeight');
// Save current and upcoming widths and outer widths
gotoData.currentWidth = getHiddenProperty(gotoData.current, 'width');
gotoData.upcomingWidth = getHiddenProperty(gotoData.upcoming, 'width');
gotoData.currentOuterWidth = getHiddenProperty(gotoData.current, 'outerWidth');
gotoData.upcomingOuterWidth = getHiddenProperty(gotoData.upcoming, 'outerWidth');
// Transition method
if (o.transition != 'basic' &&
typeof o.transition == 'string' &&
eval('typeof ' + o.transition) == 'function' ) {
// Run the passed method
eval( o.transition + '(gotoData)' );
} else {
// Default transition method
basic(gotoData);
}
// Update active item
$active = itemNumber;
// Update navigation
updateNavNum($nav);
updateNavText($nav);
// Disable default behavior
return false;
}
// Build navigation
function buildNav() {
// Check the position of the nav and insert container
if ( o.navPosition === 'above' || o.navPosition === 'both' ) {
$box.prepend('<div class="quovolve-nav quovolve-nav-above"></div>');
var nav = $box.find('.quovolve-nav');
}
if ( o.navPosition === 'below' || o.navPosition === 'both' ) {
$box.append('<div class="quovolve-nav quovolve-nav-below"></div>');
var nav = $box.find('.quovolve-nav');
}
if ( o.navPosition === 'custom' ) {
if ( o.navPositionCustom !== '' && $( o.navPositionCustom ).length !== 0 ) {
$( o.navPositionCustom ).append('<div class="quovolve-nav quovolve-nav-custom"></div>');
var nav = $( o.navPositionCustom ).find('.quovolve-nav');
} else {
console.log('Error', 'That custom selector did not return an element.');
}
}
// Previous and next navigation
if ( o.navPrev ) {
nav.append('<span class="nav-prev">' + o.navPrevText + '</span>');
}
if ( o.navNext ) {
nav.append('<span class="nav-next">' + o.navNextText + '</span>');
}
// Numbered navigation
if ( o.navNum ) {
nav.append('<ol class="nav-numbers"></ol>');
for (var i = 1; i < ($total + 1); i++ ) {
nav
.find('.nav-numbers')
.append('<li>' + i + '</li>');
}
updateNavNum(nav);
}
// Navigation description
if ( o.navText ) {
nav.append('<span class="nav-text"></span>');
updateNavText(nav);
}
return nav;
}
// Get height of a hidden element
function getHiddenProperty(item, property) {
// Default method
if (!property) property = 'height';
// Check if item was hidden
if ( $(this).is(':hidden') ) {
// Reveal the hidden item but not to the user
item.show().css({'position':'absolute', 'visibility':'hidden', 'display':'block'});
}
// Get the requested property
var value = item[property]();
// Check if item was hidden
if ( $(this).is(':hidden') ) {
// Return the originally hidden item to it's original state
item.hide().css({'position':'static', 'visibility':'visible', 'display':'none'});
}
// Return the height
return value;
}
// Equal Column Heights
function equalHeight(group) {
var tallest = 0;
group.height('auto');
group.each(function() {
if ( $(this).is(':visible') ) {
var thisHeight = $(this).height();
} else {
var thisHeight = getHiddenProperty( $(this) );
}
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}
// Update numbered navigation
function updateNavNum(nav) {
if (o.navEnabled) {
nav.find('.nav-numbers li').removeClass('active');
nav
.find('.nav-numbers a[href="#item-' + $active + '"]')
.parent()
.addClass('active');
}
}
// Update navigation description
function updateNavText(nav) {
if (o.navEnabled) {
var content = o.navTextContent.replace('#a', $active).replace('#b', $total);
nav.find('.nav-text').text(content);
}
}
// Start auto play
function autoPlay() {
$box.addClass('play');
intervalID = setInterval(function() {
gotoItem( $active + 1 );
}, o.autoPlaySpeed);
return intervalID;
}
// Pause auto play
function pauseAutoPlay(intervalID) {
if ( o.stopAutoPlay !== true ) {
$box.hover(function() {
$box.addClass('pause').removeClass('play');
clearInterval(intervalID);
}, function() {
$box.removeClass('pause').addClass('play');
clearInterval(intervalID);
intervalID = autoPlay();
});
return intervalID;
}
}
// Stop auto play
function stopAutoPlay(intervalID) {
$box.hover(function() {
$box.addClass('stop').removeClass('play');
clearInterval(intervalID);
}, function() {});
return intervalID;
}
// Transition Effects
// Basic (default) Just swaps out items with no animation
function basic(data) {
$this.css('height', data.upcomingOuterHeight);
data.current.hide();
data.upcoming.show();
if (o.equalHeight === false) {
$this.css('height', 'auto');
}
}
// Fade animation
function fade(data) {
// Set container to current item's height
$this.height(data.currentOuterHeight);
// Fade out the current container
data.current.fadeOut(o.transitionSpeed, function() {
// Resize container to upcming item's height
$this.animate({
height : data.upcomingOuterHeight
}, o.transitionSpeed, function() {
// Fade in the upcoming item
data.upcoming.fadeIn(o.transitionSpeed, function() {
// Set height of container to auto
$this.height('auto');
});
});
});
}
// Bind to the forward and back buttons
$('.nav-prev a').click(function () {
return gotoItem( $active - 1 );
});
$('.nav-next a').click(function () {
return gotoItem( $active + 1 );
});
// Bind the numbered navigation buttons
$('.nav-numbers a').click(function() {
return gotoItem( $(this).text() );
});
// Create a public interface to move to a specific item
$(this).bind('goto', function (event, item) {
gotoItem( item );
});
}); // #end of return this.each()
};
$.fn.quovolver.defaults = {
children : '', // If selector is provided, we will use the find method to get the group of items
transition : 'fade', // The style of the transition
transitionSpeed : 300, // This is the speed that each animation will take, not the entire transition
autoPlay : true, // Toggle auto rotate
autoPlaySpeed : 6000, // Duration before each transition
pauseOnHover : true, // Should the auto rotate pause on hover
stopOnHover : false, // Should the auto rotate stop on hover (and not continue after hover)
equalHeight : true, // Should every item have equal heights
navPosition : 'above', // above, below, both, custom (must provide custom selector for placement)
navPositionCustom : '', // selector of custom element
navPrev : false, // Toggle "previous" button
navNext : false, // Toggle "next" button
navNum : false, // Toggle numbered navigation
navText : false, // Toggle navigation description (e.g. display current item # and total item #)
navPrevText : 'Prev', // Text for the "previous" button
navNextText : 'Next', // Text for the "next" button
navTextContent : '#a / #b' // #a will be replaced with current and #b with total
};
})(jQuery);
and here is a very simple example of the html that works with it...
<div class="quovolver">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
Sorry it took a bit longer than anticipated ;)
Let me know if this works for you.
You can replace your current Quovolver code with the following:
$(document).ready(function() {
var $items = $('.quovolver .quote');
var quovolver = $('.quovolver');
var newItems = [];
$.each($items, function(i, quote) {
var $copy = $(quote);
newItems.push($copy);
$copy.remove();
});
var random;
var chosenRandom = [];
for (var i = 0; i < newItems.length - 1; i++) {
random = Math.floor(Math.random() * newItems.length);
while ($.inArray(random, chosenRandom) != -1) {
random = Math.floor(Math.random() * newItems.length);
}
chosenRandom.push(random);
quovolver.append(newItems[random]);
}
$('div.quovolver').quovolver({autoPlaySpeed : 6000});
});​
EDIT
To fix the overlapping divs, I have made a small adjustment in the code above, besides that, can you change the CSS Class testimonial_widget to include : overflow:hidden ? That will also aid in hiding the divs that are creeping over it.
Secondly the length of each div can be changed in the script above, when passing an object to quovolver, modify the following:
autoPlaySpeed : 6000 to however many (seconds * 1000) that you want it to wait.
Hope this helps ;)

How do I position a div next to a mouse click using JQuery?

How do I position a div next to a mouse click using JQuery?
Thanks
You can try:
$( "td").click( function(event) {
$("#divId").css( {position:"absolute", top:event.pageY, left: event.pageX});
});
After additional question was asked in the comment:
$( "td").click( function(event) {
var div = $("#divId");
div.css( {
position:"absolute",
top:event.pageY,
left: event.pageX});
var delayTimer = setTimeout( function( ) {
$that.fadeIn( "slow");
}, 100);
div.mouseover( function( event) {
if (delayTimer)
clearTimeout( delayTimer);
}).mouseout( function(){
if (delayTimer)
clearTimeout( delayTimer);
var $that = $(this);
delayTimer = setTimeout( function( ) {
$that.fadeOut( "slow");
}, 500)
});
});
Something like:
$('#cell').bind('click',
function(e){
$('#div').css('left',e.pageX + 'px' );
$('#div').css('top',e.pageY + 'px' ); });
The div's position should be set to absolute.

Categories

Resources