Slider with rslides rezising itself due to different size images - javascript

When trying use the, otherwise brilliant, rslides js plugin I bump into this annoying problem. I want the images to be imported to the site via links which means I can't resize them but the slider handles this rather poorly; it expands. Now, the slider is responsive, it scales with the page width. One solution might be to set static values for the size but I would prefer not doing this as it would probably break the responsive %scaling.
Edit: forgot to link site http://208.69.30.150/build/age_past.html
Some clarification that's come up in the comments:
The images are resized within the slider. But the slider is resizing to some of the images sizes, only on the height, this is because the images do not all have the same aspect ratios. So I want to resize the images width, and if the height overflows I want to crop of that overflow.
CSS
/*SLIDER*/
.slider{
background-color: #222;
}
.rslides_container {
position: relative;
margin: 50px auto;
width: 100%;
background: #222;
}
.slider .slider_medium{
max-width: 900px;
}
.rslides {
border-radius:200px;
-moz-border-radius:20px;
-webkit-border-radius:20px;
position: relative;
list-style: none;
overflow: hidden;
width: 100%;
padding: 0;
margin: 0 auto;
}
.rslides li {
-webkit-backface-visibility: hidden;
position: absolute;
display: none;
width: 100%;
left: 0;
top: 0;
}
.rslides li:first-child {
position: relative;
display: block;
float: left;
}
.rslides img {
display: block;
height: auto;
float: left;
width: 100%;
border: 0;
}
/*SLIDER OVERLAY IMAGES*/
#banner_image_1 img{
position: absolute;
z-index: 5;
top: 10%;
left: 3%;
height:auto;
width:auto;
max-height: 100px;
background: #FFF;
}
#banner_image_2 img{
position: absolute;
z-index: 5;
bottom: 3%;
right: 1%;
height: 20%;
max-height:60px;
}
#banner_image_3 img{
position: absolute;
z-index: 5;
bottom: 3%;
right: 7%;
height: 20%;
max-height:60px;
}
HTML
<div class="block slider">
<div class="rslides_container slider_medium">
<!--<a id="banner_image_1" href="" target="">
<img src="">
</a>-->
<ul class="rslides">
<li>
<a href="http://www.agepast.com/">
<img src="http://fc00.deviantart.net/fs70/i/2010/194/2/5/Age_Past_Wallpaper_by_Tsabo6.jpg"/>
</a>
</li>
<li>
<a href="http://www.agepast.com/">
<img src="http://fc03.deviantart.net/fs71/i/2011/211/c/6/age_past_by_tsabo6-d424m3v.jpg"/>
</a>
</li>
<li>
<a href="http://www.agepast.com/">
<img src="http://fc00.deviantart.net/fs70/i/2010/257/7/e/age_past_earth_magic_by_tsabo6-d2yp0v0.jpg"/>
</a>
</li>
<li>
<a href="http://www.agepast.com/">
<img src="http://fc01.deviantart.net/fs71/i/2010/244/8/2/age_past_wall_2_by_tsabo6-d2xr9g0.jpg"/>
</a>
</li>
</ul>
</div>
<script>
$(function() {
$(".rslides").responsiveSlides({
auto: true, speed: 1500, timeout: 5000, pause: true,
});
});
</script>
</div>
& LOTS of JS (which just won't be formatted right.)
(function ($, window, i) {
$.fn.responsiveSlides = function (options) {
// Default settings
var settings = $.extend({
"auto": true, // Boolean: Animate automatically, true or false
"speed": 500, // Integer: Speed of the transition, in milliseconds
"timeout": 4000, // Integer: Time between slide transitions, in milliseconds
"pager": false, // Boolean: Show pager, true or false
"nav": false, // Boolean: Show navigation, true or false
"random": false, // Boolean: Randomize the order of the slides, true or false
"pause": false, // Boolean: Pause on hover, true or false
"pauseControls": true, // Boolean: Pause when hovering controls, true or false
"prevText": "Previous", // String: Text for the "previous" button
"nextText": "Next", // String: Text for the "next" button
"maxwidth": "", // Integer: Max-width of the slideshow, in pixels
"navContainer": "", // Selector: Where auto generated controls should be appended to, default is after the <ul>
"manualControls": "", // Selector: Declare custom pager navigation
"namespace": "rslides", // String: change the default namespace used
"before": $.noop, // Function: Before callback
"after": $.noop // Function: After callback
}, options);
return this.each(function () {
// Index for namespacing
i++;
var $this = $(this),
// Local variables
vendor,
selectTab,
startCycle,
restartCycle,
rotate,
$tabs,
// Helpers
index = 0,
$slide = $this.children(),
length = $slide.size(),
fadeTime = parseFloat(settings.speed),
waitTime = parseFloat(settings.timeout),
maxw = parseFloat(settings.maxwidth),
// Namespacing
namespace = settings.namespace,
namespaceIdx = namespace + i,
// Classes
navClass = namespace + "_nav " + namespaceIdx + "_nav",
activeClass = namespace + "_here",
visibleClass = namespaceIdx + "_on",
slideClassPrefix = namespaceIdx + "_s",
// Pager
$pager = $("<ul class='" + namespace + "_tabs " + namespaceIdx + "_tabs' />"),
// Styles for visible and hidden slides
visible = {"float": "left", "position": "relative", "opacity": 1, "zIndex": 2},
hidden = {"float": "none", "position": "absolute", "opacity": 0, "zIndex": 1},
// Detect transition support
supportsTransitions = (function () {
var docBody = document.body || document.documentElement;
var styles = docBody.style;
var prop = "transition";
if (typeof styles[prop] === "string") {
return true;
}
// Tests for vendor specific prop
vendor = ["Moz", "Webkit", "Khtml", "O", "ms"];
prop = prop.charAt(0).toUpperCase() + prop.substr(1);
var i;
for (i = 0; i < vendor.length; i++) {
if (typeof styles[vendor[i] + prop] === "string") {
return true;
}
}
return false;
})(),
// Fading animation
slideTo = function (idx) {
settings.before(idx);
// If CSS3 transitions are supported
if (supportsTransitions) {
$slide
.removeClass(visibleClass)
.css(hidden)
.eq(idx)
.addClass(visibleClass)
.css(visible);
index = idx;
setTimeout(function () {
settings.after(idx);
}, fadeTime);
// If not, use jQuery fallback
} else {
$slide
.stop()
.fadeOut(fadeTime, function () {
$(this)
.removeClass(visibleClass)
.css(hidden)
.css("opacity", 1);
})
.eq(idx)
.fadeIn(fadeTime, function () {
$(this)
.addClass(visibleClass)
.css(visible);
settings.after(idx);
index = idx;
});
}
};
// Random order
if (settings.random) {
$slide.sort(function () {
return (Math.round(Math.random()) - 0.5);
});
$this
.empty()
.append($slide);
}
// Add ID's to each slide
$slide.each(function (i) {
this.id = slideClassPrefix + i;
});
// Add max-width and classes
$this.addClass(namespace + " " + namespaceIdx);
if (options && options.maxwidth) {
$this.css("max-width", maxw);
}
// Hide all slides, then show first one
$slide
.hide()
.css(hidden)
.eq(0)
.addClass(visibleClass)
.css(visible)
.show();
// CSS transitions
if (supportsTransitions) {
$slide
.show()
.css({
// -ms prefix isn't needed as IE10 uses prefix free version
"-webkit-transition": "opacity " + fadeTime + "ms ease-in-out",
"-moz-transition": "opacity " + fadeTime + "ms ease-in-out",
"-o-transition": "opacity " + fadeTime + "ms ease-in-out",
"transition": "opacity " + fadeTime + "ms ease-in-out"
});
}
// Only run if there's more than one slide
if ($slide.size() > 1) {
// Make sure the timeout is at least 100ms longer than the fade
if (waitTime < fadeTime + 100) {
return;
}
// Pager
if (settings.pager && !settings.manualControls) {
var tabMarkup = [];
$slide.each(function (i) {
var n = i + 1;
tabMarkup +=
"<li>" +
"<a href='#' class='" + slideClassPrefix + n + "'>" + n + "</a>" +
"</li>";
});
$pager.append(tabMarkup);
// Inject pager
if (options.navContainer) {
$(settings.navContainer).append($pager);
} else {
$this.after($pager);
}
}
// Manual pager controls
if (settings.manualControls) {
$pager = $(settings.manualControls);
$pager.addClass(namespace + "_tabs " + namespaceIdx + "_tabs");
}
// Add pager slide class prefixes
if (settings.pager || settings.manualControls) {
$pager.find('li').each(function (i) {
$(this).addClass(slideClassPrefix + (i + 1));
});
}
// If we have a pager, we need to set up the selectTab function
if (settings.pager || settings.manualControls) {
$tabs = $pager.find('a');
// Select pager item
selectTab = function (idx) {
$tabs
.closest("li")
.removeClass(activeClass)
.eq(idx)
.addClass(activeClass);
};
}
// Auto cycle
if (settings.auto) {
startCycle = function () {
rotate = setInterval(function () {
// Clear the event queue
$slide.stop(true, true);
var idx = index + 1 < length ? index + 1 : 0;
// Remove active state and set new if pager is set
if (settings.pager || settings.manualControls) {
selectTab(idx);
}
slideTo(idx);
}, waitTime);
};
// Init cycle
startCycle();
}
// Restarting cycle
restartCycle = function () {
if (settings.auto) {
// Stop
clearInterval(rotate);
// Restart
startCycle();
}
};
// Pause on hover
if (settings.pause) {
$this.hover(function () {
clearInterval(rotate);
}, function () {
restartCycle();
});
}
// Pager click event handler
if (settings.pager || settings.manualControls) {
$tabs.bind("click", function (e) {
e.preventDefault();
if (!settings.pauseControls) {
restartCycle();
}
// Get index of clicked tab
var idx = $tabs.index(this);
// Break if element is already active or currently animated
if (index === idx || $("." + visibleClass).queue('fx').length) {
return;
}
// Remove active state from old tab and set new one
selectTab(idx);
// Do the animation
slideTo(idx);
})
.eq(0)
.closest("li")
.addClass(activeClass);
// Pause when hovering pager
if (settings.pauseControls) {
$tabs.hover(function () {
clearInterval(rotate);
}, function () {
restartCycle();
});
}
}
// Navigation
if (settings.nav) {
var navMarkup =
"<a href='#' class='" + navClass + " prev'>" + settings.prevText + "</a>" +
"<a href='#' class='" + navClass + " next'>" + settings.nextText + "</a>";
// Inject navigation
if (options.navContainer) {
$(settings.navContainer).append(navMarkup);
} else {
$this.after(navMarkup);
}
var $trigger = $("." + namespaceIdx + "_nav"),
$prev = $trigger.filter(".prev");
// Click event handler
$trigger.bind("click", function (e) {
e.preventDefault();
var $visibleClass = $("." + visibleClass);
// Prevent clicking if currently animated
if ($visibleClass.queue('fx').length) {
return;
}
// Adds active class during slide animation
// $(this)
// .addClass(namespace + "_active")
// .delay(fadeTime)
// .queue(function (next) {
// $(this).removeClass(namespace + "_active");
// next();
// });
// Determine where to slide
var idx = $slide.index($visibleClass),
prevIdx = idx - 1,
nextIdx = idx + 1 < length ? index + 1 : 0;
// Go to slide
slideTo($(this)[0] === $prev[0] ? prevIdx : nextIdx);
if (settings.pager || settings.manualControls) {
selectTab($(this)[0] === $prev[0] ? prevIdx : nextIdx);
}
if (!settings.pauseControls) {
restartCycle();
}
});
// Pause when hovering navigation
if (settings.pauseControls) {
$trigger.hover(function () {
clearInterval(rotate);
}, function () {
restartCycle();
});
}
}
}
// Max-width fallback
if (typeof document.body.style.maxWidth === "undefined" && options.maxwidth) {
var widthSupport = function () {
$this.css("width", "100%");
if ($this.width() > maxw) {
$this.css("width", maxw);
}
};
// Init fallback
widthSupport();
$(window).bind("resize", function () {
widthSupport();
});
}
});
};
})(jQuery, this, 0);

I think you can add width: auto; and overflow: hidden to your slider container

I could not find a proper solution. I solved my issue by switching slider. If anyone finds an answer please do share, meanwhile I suggest trying this: http://www.builtbyevolve.com/work/plugins/nerve-slider

Related

Ticker-style getting cut in Mobile View

The requirement is to sow the information continuously hence opted for a ticker style.
Now I am using an [ticker-style.css] along with [jquery.ticker.js]
It works fine in a Full Screen however while browsing in a Mobile/Tabler - the text is getting cut (see below screenshot) - I tried to play around the width however the rendering was not as expected.
Can you help here.
Thanks in advance.
/*
jQuery News Ticker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2 of the License.
jQuery News Ticker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with jQuery News Ticker. If not, see <http://www.gnu.org/licenses/>.
*/
(function($){
$.fn.ticker = function(options) {
// Extend our default options with those provided.
// Note that the first arg to extend is an empty object -
// this is to keep from overriding our "defaults" object.
var opts = $.extend({}, $.fn.ticker.defaults, options);
// check that the passed element is actually in the DOM
if ($(this).length == 0) {
if (window.console && window.console.log) {
window.console.log('Element does not exist in DOM!');
}
else {
alert('Element does not exist in DOM!');
}
return false;
}
/* Get the id of the UL to get our news content from */
var newsID = '#' + $(this).attr('id');
/* Get the tag type - we will check this later to makde sure it is a UL tag */
var tagType = $(this).get(0).tagName;
return this.each(function() {
// get a unique id for this ticker
var uniqID = getUniqID();
/* Internal vars */
var settings = {
position: 0,
time: 0,
distance: 0,
newsArr: {},
play: true,
paused: false,
contentLoaded: false,
dom: {
contentID: '#ticker-content-' + uniqID,
titleID: '#ticker-title-' + uniqID,
titleElem: '#ticker-title-' + uniqID + ' SPAN',
tickerID : '#ticker-' + uniqID,
wrapperID: '#ticker-wrapper-' + uniqID,
revealID: '#ticker-swipe-' + uniqID,
revealElem: '#ticker-swipe-' + uniqID + ' SPAN',
controlsID: '#ticker-controls-' + uniqID,
prevID: '#prev-' + uniqID,
nextID: '#next-' + uniqID,
playPauseID: '#play-pause-' + uniqID
}
};
// if we are not using a UL, display an error message and stop any further execution
if (tagType != 'UL' && tagType != 'OL' && opts.htmlFeed === true) {
debugError('Cannot use <' + tagType.toLowerCase() + '> type of element for this plugin - must of type <ul> or <ol>');
return false;
}
// set the ticker direction
opts.direction == 'rtl' ? opts.direction = 'right' : opts.direction = 'left';
// lets go...
initialisePage();
/* Function to get the size of an Object*/
function countSize(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
function getUniqID() {
var newDate = new Date;
return newDate.getTime();
}
/* Function for handling debug and error messages */
function debugError(obj) {
if (opts.debugMode) {
if (window.console && window.console.log) {
window.console.log(obj);
}
else {
alert(obj);
}
}
}
/* Function to setup the page */
function initialisePage() {
// process the content for this ticker
processContent();
// add our HTML structure for the ticker to the DOM
$(newsID).wrap('<div id="' + settings.dom.wrapperID.replace('#', '') + '"></div>');
// remove any current content inside this ticker
$(settings.dom.wrapperID).children().remove();
$(settings.dom.wrapperID).append('<div id="' + settings.dom.tickerID.replace('#', '') + '" class="ticker"><div id="' + settings.dom.titleID.replace('#', '') + '" class="ticker-title"><span><!-- --></span></div><p id="' + settings.dom.contentID.replace('#', '') + '" class="ticker-content"></p><div id="' + settings.dom.revealID.replace('#', '') + '" class="ticker-swipe"><span><!-- --></span></div></div>');
$(settings.dom.wrapperID).removeClass('no-js').addClass('ticker-wrapper has-js ' + opts.direction);
// hide the ticker
$(settings.dom.tickerElem + ',' + settings.dom.contentID).hide();
// add the controls to the DOM if required
if (opts.controls) {
// add related events - set functions to run on given event
$(settings.dom.controlsID).on('click mouseover mousedown mouseout mouseup', function (e) {
var button = e.target.id;
if (e.type == 'click') {
switch (button) {
case settings.dom.prevID.replace('#', ''):
// show previous item
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
manualChangeContent('prev');
break;
case settings.dom.nextID.replace('#', ''):
// show next item
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
manualChangeContent('next');
break;
case settings.dom.playPauseID.replace('#', ''):
// play or pause the ticker
if (settings.play == true) {
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
pauseTicker();
}
else {
settings.paused = false;
$(settings.dom.playPauseID).removeClass('paused');
restartTicker();
}
break;
}
}
else if (e.type == 'mouseover' && $('#' + button).hasClass('controls')) {
$('#' + button).addClass('over');
}
else if (e.type == 'mousedown' && $('#' + button).hasClass('controls')) {
$('#' + button).addClass('down');
}
else if (e.type == 'mouseup' && $('#' + button).hasClass('controls')) {
$('#' + button).removeClass('down');
}
else if (e.type == 'mouseout' && $('#' + button).hasClass('controls')) {
$('#' + button).removeClass('over');
}
});
// add controls HTML to DOM
$(settings.dom.wrapperID).append('<ul id="' + settings.dom.controlsID.replace('#', '') + '" class="ticker-controls"><li id="' + settings.dom.playPauseID.replace('#', '') + '" class="jnt-play-pause controls"><!-- --></li><li id="' + settings.dom.prevID.replace('#', '') + '" class="jnt-prev controls"><!-- --></li><li id="' + settings.dom.nextID.replace('#', '') + '" class="jnt-next controls"><!-- --></li></ul>');
}
if (opts.displayType != 'fade') {
// add mouse over on the content
$(settings.dom.contentID).mouseover(function () {
if (settings.paused == false) {
pauseTicker();
}
}).mouseout(function () {
if (settings.paused == false) {
restartTicker();
}
});
}
// we may have to wait for the ajax call to finish here
if (!opts.ajaxFeed) {
setupContentAndTriggerDisplay();
}
}
/* Start to process the content for this ticker */
function processContent() {
// check to see if we need to load content
if (settings.contentLoaded == false) {
// construct content
if (opts.ajaxFeed) {
if (opts.feedType == 'xml') {
$.ajax({
url: opts.feedUrl,
cache: false,
dataType: opts.feedType,
async: true,
success: function(data){
count = 0;
// get the 'root' node
for (var a = 0; a < data.childNodes.length; a++) {
if (data.childNodes[a].nodeName == 'rss') {
xmlContent = data.childNodes[a];
}
}
// find the channel node
for (var i = 0; i < xmlContent.childNodes.length; i++) {
if (xmlContent.childNodes[i].nodeName == 'channel') {
xmlChannel = xmlContent.childNodes[i];
}
}
// for each item create a link and add the article title as the link text
for (var x = 0; x < xmlChannel.childNodes.length; x++) {
if (xmlChannel.childNodes[x].nodeName == 'item') {
xmlItems = xmlChannel.childNodes[x];
var title, link = false;
for (var y = 0; y < xmlItems.childNodes.length; y++) {
if (xmlItems.childNodes[y].nodeName == 'title') {
title = xmlItems.childNodes[y].lastChild.nodeValue;
}
else if (xmlItems.childNodes[y].nodeName == 'link') {
link = xmlItems.childNodes[y].lastChild.nodeValue;
}
if ((title !== false && title != '') && link !== false) {
settings.newsArr['item-' + count] = { type: opts.titleText, content: '' + title + '' }; count++; title = false; link = false;
}
}
}
}
// quick check here to see if we actually have any content - log error if not
if (countSize(settings.newsArr < 1)) {
debugError('Couldn\'t find any content from the XML feed for the ticker to use!');
return false;
}
settings.contentLoaded = true;
setupContentAndTriggerDisplay();
}
});
}
else {
debugError('Code Me!');
}
}
else if (opts.htmlFeed) {
if($(newsID + ' LI').length > 0) {
$(newsID + ' LI').each(function (i) {
// maybe this could be one whole object and not an array of objects?
settings.newsArr['item-' + i] = { type: opts.titleText, content: $(this).html()};
});
}
else {
debugError('Couldn\'t find HTML any content for the ticker to use!');
return false;
}
}
else {
debugError('The ticker is set to not use any types of content! Check the settings for the ticker.');
return false;
}
}
}
function setupContentAndTriggerDisplay() {
settings.contentLoaded = true;
// update the ticker content with the correct item
// insert news content into DOM
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
// set the next content item to be used - loop round if we are at the end of the content
if (settings.position == (countSize(settings.newsArr) -1)) {
settings.position = 0;
}
else {
settings.position++;
}
// get the values of content and set the time of the reveal (so all reveals have the same speed regardless of content size)
distance = $(settings.dom.contentID).width();
time = distance / opts.speed;
// start the ticker animation
revealContent();
}
// slide back cover or fade in content
function revealContent() {
$(settings.dom.contentID).css('opacity', '1');
if(settings.play) {
// get the width of the title element to offset the content and reveal
var offset = $(settings.dom.titleID).width() + 20;
$(settings.dom.revealID).css(opts.direction, offset + 'px');
// show the reveal element and start the animation
if (opts.displayType == 'fade') {
// fade in effect ticker
$(settings.dom.revealID).hide(0, function () {
$(settings.dom.contentID).css(opts.direction, offset + 'px').fadeIn(opts.fadeInSpeed, postReveal);
});
}
else if (opts.displayType == 'scroll') {
// to code
}
else {
// default bbc scroll effect
$(settings.dom.revealElem).show(0, function () {
$(settings.dom.contentID).css(opts.direction, offset + 'px').show();
// set our animation direction
animationAction = opts.direction == 'right' ? { marginRight: distance + 'px'} : { marginLeft: distance + 'px' };
$(settings.dom.revealID).css('margin-' + opts.direction, '0px').delay(20).animate(animationAction, time, 'linear', postReveal);
});
}
}
else {
return false;
}
};
// here we hide the current content and reset the ticker elements to a default state ready for the next ticker item
function postReveal() {
if(settings.play) {
// we have to separately fade the content out here to get around an IE bug - needs further investigation
$(settings.dom.contentID).delay(opts.pauseOnItems).fadeOut(opts.fadeOutSpeed);
// deal with the rest of the content, prepare the DOM and trigger the next ticker
if (opts.displayType == 'fade') {
$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
$(settings.dom.wrapperID)
.find(settings.dom.revealElem + ',' + settings.dom.contentID)
.hide()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.show()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.removeAttr('style');
setupContentAndTriggerDisplay();
});
}
else {
$(settings.dom.revealID).hide(0, function () {
$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
$(settings.dom.wrapperID)
.find(settings.dom.revealElem + ',' + settings.dom.contentID)
.hide()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.show()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.removeAttr('style');
setupContentAndTriggerDisplay();
});
});
}
}
else {
$(settings.dom.revealElem).hide();
}
}
// pause ticker
function pauseTicker() {
settings.play = false;
// stop animation and show content - must pass "true, true" to the stop function, or we can get some funky behaviour
$(settings.dom.tickerID + ',' + settings.dom.revealID + ',' + settings.dom.titleID + ',' + settings.dom.titleElem + ',' + settings.dom.revealElem + ',' + settings.dom.contentID).stop(true, true);
$(settings.dom.revealID + ',' + settings.dom.revealElem).hide();
$(settings.dom.wrapperID)
.find(settings.dom.titleID + ',' + settings.dom.titleElem).show()
.end().find(settings.dom.contentID).show();
}
// play ticker
function restartTicker() {
settings.play = true;
settings.paused = false;
// start the ticker again
postReveal();
}
// change the content on user input
function manualChangeContent(direction) {
pauseTicker();
switch (direction) {
case 'prev':
if (settings.position == 0) {
settings.position = countSize(settings.newsArr) -2;
}
else if (settings.position == 1) {
settings.position = countSize(settings.newsArr) -1;
}
else {
settings.position = settings.position - 2;
}
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
break;
case 'next':
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
break;
}
// set the next content item to be used - loop round if we are at the end of the content
if (settings.position == (countSize(settings.newsArr) -1)) {
settings.position = 0;
}
else {
settings.position++;
}
}
});
};
// plugin defaults - added as a property on our plugin function
$.fn.ticker.defaults = {
speed: 0.10,
ajaxFeed: false,
feedUrl: '',
feedType: 'xml',
displayType: 'reveal',
htmlFeed: true,
debugMode: true,
controls: true,
titleText: '',
direction: 'ltr',
pauseOnItems: 3000,
fadeInSpeed: 600,
fadeOutSpeed: 300
};
})(jQuery);
/* Ticker Styling */
.ticker-wrapper.has-js {
margin: 0;
padding: 0;
width: 780px;
height: 32px;
display: block;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
background-color:inherit;
font-size: inherit;
}
.ticker {
width: 710px;
height: 23px;
display: block;
position: relative;
overflow: hidden;
background-color: #fff;
#media #{$xs}{
width: 200px;
}
}
.ticker-title {
padding-top: 9px;
color: #990000;
font-weight: bold;
background-color: #fff;
text-transform: capitalize;
}
.ticker-content {
margin: 0px;
/* padding-top: 9px; */
position: absolute;
color: #506172;
font-weight: normal;
background-color: #fff;
overflow: hidden;
white-space: nowrap;
font-family: "Roboto",sans-serif;
font-size: 16px;
}
.ticker-content:focus {
none;
}
.ticker-content a {
text-decoration: none;
color: #1F527B;
}
.ticker-content a:hover {
text-decoration: underline;
color: #0D3059;
}
.ticker-swipe {
padding-top: 9px;
position: absolute;
top: 0px;
background-color: #fff;
display: block;
width: 800px;
height: 23px;
}
.ticker-swipe span {
margin-left: 1px;
background-color: #fff;
border-bottom: 1px solid #1F527B;
height: 12px;
width: 7px;
display: block;
}
.ticker-controls {
padding: 8px 0px 0px 0px;
list-style-type: none;
float: left;
}
.ticker-controls li {
padding: 0px;
margin-left: 5px;
float: left;
cursor: pointer;
height: 16px;
width: 16px;
display: block;
}
.ticker-controls li.jnt-play-pause {
background-image: url('../images/controls.png');
background-position: 32px 16px;
}
.ticker-controls li.jnt-play-pause.over {
background-position: 32px 32px;
}
.ticker-controls li.jnt-play-pause.down {
background-position: 32px 0px;
}
.ticker-controls li.jnt-play-pause.paused {
background-image: url('../images/controls.png');
background-position: 48px 16px;
}
.ticker-controls li.jnt-play-pause.paused.over {
background-position: 48px 32px;
}
.ticker-controls li.jnt-play-pause.paused.down {
background-position: 48px 0px;
}
.ticker-controls li.jnt-prev {
background-image: url('../images/controls.png');
background-position: 0px 16px;
}
.ticker-controls li.jnt-prev.over {
background-position: 0px 32px;
}
.ticker-controls li.jnt-prev.down {
background-position: 0px 0px;
}
.ticker-controls li.jnt-next {
background-image: url('../images/controls.png');
background-position: 16px 16px;
}
.ticker-controls li.jnt-next.over {
background-position: 16px 32px;
}
.ticker-controls li.jnt-next.down {
background-position: 16px 0px;
}
.js-hidden {
display: none;
}
.no-js-news {
padding: 10px 0px 0px 45px;
color: #fff;
}
.left .ticker-swipe {
/*left: 80px;*/
}
.left .ticker-controls, .left .ticker-content, .left .ticker-title, .left .ticker {
float: left;
}
.left .ticker-controls {
padding-left: 6px;
}
.right .ticker-swipe {
/*right: 80px;*/
}
.right .ticker-controls, .right .ticker-content, .right .ticker-title, .right .ticker {
float: right;
}
.right .ticker-controls {
padding-right: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>Trending now</strong>
<!-- <p>Rem ipsum dolor sit amet, consectetur adipisicing elit.</p> -->
<div class="trending-animated">
<ul id="js-news" class="js-hidden">
<li class="news-item">Dolor sit amet, consectetur adipisicing elit.</li>
<li class="news-item">Spondon IT sit amet, consectetur.......</li>
<li class="news-item">Rem ipsum dolor sit amet, consectetur adipisicing elit.</li>
</ul>
</div>
The problem is that you are setting fixed widths for ticker elements.The ticker container has a width of 720px no matter what size the screen, and on screens < 767px the container for the scrolling text is just 230px.
Either change the CSS if it is your own, or if not you can add these rules after the Ticker CSS in included:
#media (max-width: 767px){
.ticker-wrapper.has-js,
.ticker,
.trending-tittle .ticker {
width: 100%!important;
}
}
This sets them to use the full width of the screen.

jquery Multiple text scroll on div hover not work

I have This Code for scroll text on hover div using jQuery:
HTML:
<div id="target" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText1">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
<br>
<div id="target" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText1">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
<br>
<div id="target" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText1">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
JS:
$(function()
{
$(".tooMuchText1").hoverForMore({
"speed": 300,
"loop": false,
"target":'#target'
});
});
CSS:
.tooMuchText {
overflow: hidden;
white-space: nowrap;
display: block;
text-align: left;
text-overflow: ellipsis;
cursor: default;
}
So, I need to Scroll multiple(for each) div text on hover with target id. But My code Work only in first div with target id. how do can I fox this problem ?!
Demo jsfiddle
This is just example can you try multiple class in div ? if yes than i have try this in js fiddle please check.. if it may help you
(function($, window) {
var isjQuery = !!$.fn.jquery;
var isFirefox = /Firefox/.test(navigator.userAgent);
var isMobile = /Mobile/.test(navigator.userAgent);
var defaults = {
"speed": 60.0,
"gap": 20,
"loop": true,
"removeTitle": true,
"snapback": true,
"alwaysOn": false,
"addStyles": true,
"target": true,
"startEvent": isMobile ? "touchstart" : (isjQuery ? "mouseenter" : "mouseover"),
"stopEvent": isMobile ? "touchend" : (isjQuery ? "mouseleave" : "mouseout")
};
$.fn['hoverForMore'] = function(options) {
var self = this;
var head = document.getElementsByTagName('head')[0];
var originalOverflow, originalOverflowParent, startTime;
options = $.extend({}, defaults, options);
var targetSelector = options.target || self.selector;
// Always-on without looping is just silly
if (options.alwaysOn) {
options.loop = true;
options.startEvent = "startLooping"; // only triggered programmatically
}
// Detect CSS prefix and presence of CSS animation
var hasAnimation = document.body.style.animationName ? true : false,
animationString = 'animation',
transitionString = 'transition',
transformString = 'transform',
keyframePrefix = '',
domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
pfx = '';
// Find the CSS prefix, if necessary
if (hasAnimation === false)
for (var i = 0; i < domPrefixes.length; i++) {
if (document.body.style[domPrefixes[i] + 'AnimationName'] === undefined)
continue;
pfx = domPrefixes[i];
animationString = pfx + 'Animation';
transitionString = pfx + 'Transition';
transformString = pfx + 'Transform';
cssPrefix = '-' + pfx.toLowerCase() + '-';
hasAnimation = true;
break;
}
// Auto-add ellipsis and such
if (options.addStyles) {
head.appendChild($(
'<style type="text/css">' + self.selector + '{' + 'cursor:default;' + 'text-align:left;' + 'display:block;' + 'overflow:hidden;' + 'white-space:nowrap;' + 'text-overflow:ellipsis;' + cssPrefix + 'user-select: none;' + '}</style>')[0]);
}
// Non-animation fallback. TODO: Animate with jQuery instead
if (!hasAnimation) {
// Fallback to title text hover
$(options.target || self.selector).each(function(n, el) {
var $el = $(el);
$el.attr("title", $.trim($el.text()));
});
return self;
}
// Keyframes are only used in loop mode
if (options.loop) {
// Attach global style
var $keyframeStyle = $('<style type="text/css"></style>');
var $keyframeStyleReverse = $('<style type="text/css"></style>');
head.appendChild($keyframeStyle[0]);
head.appendChild($keyframeStyleReverse[0]);
}
// For non-loop mode, set an empty transform value (FireFox needs this to transition properly)
else {
$(self.selector).each(function(n, el) {
el.style[transformString] = 'translateX(0px)';
});
}
// Attach start event
$(targetSelector).on(options.startEvent, function(e) {
startTime = (new Date()).getTime();
// Get hovered item, and ensure that it contains an overflown item
var $item = $(options.target ? self.selector : this).filter(":first");
if (!$item.length) return true;
var $parent = $item.parent();
var pixelDiff = $item[0].scrollWidth - $item.width();
if (pixelDiff <= 0) // && !options.alwaysOn // TODO: <marquee> without overflow
return true;
if (options.removeTitle) $item.removeAttr("title");
// Over-ride the text overflow, and cache the overflow css that we started with
originalOverflowParent = originalOverflowParent || $parent.css("overflow");
originalOverflow = originalOverflow || $item.css("overflow");
$parent.css("overflow", "hidden");
if (isMobile && options.addStyles)
$('body').css(cssPrefix + "user-select", "none");
$item
.css("overflow", "visible")
.addClass("scrolling");
if (options.loop) {
// Remove a previous clone
$item.children(".hoverForMoreContent").remove();
// Attach a duplicate string which will allow content to appear wrapped
var $contentClone = $('<span class="hoverForMoreContent" />')
.css({
"paddingLeft": parseInt(options.gap) + "px"
})
.text($item.text());
$item.append($contentClone);
var contentWidth = ($contentClone.width() + parseInt(options.gap));
// Build keyframe string and attach to global style
var keyframes = '#' + cssPrefix + 'keyframes hoverForMoreSlide { ' + 'from {' + cssPrefix + 'transform:translateX( 0 ) }' + 'to {' + cssPrefix + 'transform:translateX( -' + contentWidth + 'px ) }' + '}';
$keyframeStyle[0].innerHTML = keyframes;
// Go go gadget animation!
var sec = contentWidth / parseFloat(options.speed);
$item[0].style[animationString] = 'hoverForMoreSlide ' + sec + 's linear infinite';
} else // if(!options.loop)
{
var sec = pixelDiff / parseFloat(options.speed);
// Apply transition + transform instead of looping
$item[0].style[transitionString] = cssPrefix + 'transform ' + sec + 's linear';
// Alas, Firefox won't honor the transition immediately
if (!isFirefox)
$item[0].style[transformString] = 'translateX(-' + pixelDiff + 'px)';
else setTimeout(function() {
$item[0].style[transformString] = 'translateX(-' + pixelDiff + 'px)';
}, 0);
}
});
// Attach stop event
if (!options.alwaysOn)
$(targetSelector).on(options.stopEvent, function(e) {
var $item = $(options.target ? self.selector : this).filter(":first");
if (!$item.length) return true;
if (options.loop) {
if (options.snapback) {
// Reverse our animation
var contentWidth = $item.children('.hoverForMoreContent').width() + parseInt(options.gap);
var timeDiff = ((new Date()).getTime() - startTime) * 0.001;
var offsetX = (timeDiff * options.speed) % contentWidth;
var switchDirection = offsetX > (contentWidth / 2);
// Build keyframe string and attach to global style
var keyframes = '#' + cssPrefix + 'keyframes hoverForMoreSlideReverse { ' + 'from {' + cssPrefix + 'transform:translateX( ' + (0 - offsetX) + 'px ) }' + 'to {' + cssPrefix + 'transform:translateX( ' + (switchDirection ? 0 - contentWidth : 0) + 'px ) }' + '}';
$keyframeStyleReverse[0].innerHTML = keyframes;
var sec = (switchDirection ? contentWidth - offsetX : offsetX) * 0.2 / parseFloat(options.speed);
$item[0].style[animationString] = 'hoverForMoreSlideReverse ' + (sec > 1 ? 1 : sec) + 's linear';
$item.removeClass("scrolling");
// After animation resolves, restore original overflow setting, and remove the cloned element
setTimeout(function() {
if ($item.is(".scrolling")) return;
$item
.children(".hoverForMoreContent")
.remove();
$item.css("overflow", originalOverflow);
$item.parent().css("overflow", originalOverflowParent);
if (isMobile && options.addStyles)
$('body').css(cssPrefix + "user-select", 'text');
}, (sec * 1000) - -50);
} else // if(!options.snapback)
{
$item[0].style[animationString] = '';
$item
.css("overflow", originalOverflow)
.find(".hoverForMoreContent")
.remove();
$item.parent().css("overflow", originalOverflowParent);
if (isMobile && options.addStyles)
$('body').css(cssPrefix + "user-select", 'text');
}
} else // if(!options.loop)
{
var timeDiff = ((new Date()).getTime() - startTime) / 1000.0;
var match = $item[0].style[transitionString].match(/transform (.*)s/);
var sec = (match && match[1] && parseFloat(match[1]) < timeDiff) ? parseFloat(match[1]) : timeDiff;
sec *= 0.5;
if (!options.snapback)
$item[0].style[transitionString] = '';
else
$item[0].style[transitionString] = cssPrefix + 'transform ' + sec + 's linear';
$item.removeClass("scrolling")
// Firefox needs a delay for the transition to take effect
if (!isFirefox)
$item[0].style[transformString] = 'translateX(0px)';
else setTimeout(function() {
$item[0].style[transformString] = 'translateX(0px)';
}, 0);
if (!options.snapback) {
$item.css("overflow", originalOverflow);
if (isMobile && options.addStyles)
$('body').css(cssPrefix + "user-select", 'text');
} else // if(options.snapback)
{
setTimeout(function() {
if ($item.is(".scrolling")) return;
$item.css("overflow", originalOverflow);
if (isMobile && options.addStyles)
$('body').css(cssPrefix + "user-select", 'text');
}, sec * 1000);
}
}
});
// To manually refresh active elements when in always-on mode
self.refresh = function() {
$(self.selector).each(function(n, el) {
$(el).not(".scrolling").trigger(options.startEvent);
})
};
// Always-on mode, activate! <marquee>, eat your heart out.
if (options.alwaysOn)
self.refresh();
return self;
};
})(window.jQuery || $);
$(function() {
$(".tooMuchText1").hoverForMore({
"speed": 300,
"loop": false,
"target": '#target'
});
$(".tooMuchText2").hoverForMore({
"speed": 300,
"loop": false,
"target": '#target1'
});
$(".tooMuchText3").hoverForMore({
"speed": 300,
"loop": false,
"target": '#target2'
});
});
.tooMuchText {
overflow: hidden;
white-space: nowrap;
display: block;
text-align: left;
text-overflow: ellipsis;
cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText1">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
<br>
<div id="target1" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText2">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
<br>
<div id="target2" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText3">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
There is at least one conceptual problem here:
id's should always be unique - for identical items, use classes
There are obviously more elegant ways to do this, but latching onto your use of id's, you can expand that, and iterate through the spans, gather their unique ID, then grab the unique ID of the parent, using that as the target.
$(function() {
$(".tooMuchText").each(function() {
var thisParentId = $(this).parents("div").attr("id");
var thisId = $(this).attr("id");
$('#' + thisId).hoverForMore({
"speed": 300,
"loop": false,
"target": '#' + thisParentId
});
});
});
To finish this up, just add a unique id to each of your SPANs and DIVs.
<div id="target3" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span id='tooMuchText3' class="tooMuchText">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>

jquery fadeIn/Out, custom slideshow glitches, fade memory? fade queue?

I am building a background img slideshow and running into glitches I can't comprehend.
I have several objects that contains a list of images. I have two functions that will take these images, create one div per each, and add the imgs as background of these divs, all within a container.
Then, as described in this website, I fadeout the first div,and fadeIn the second, then move the first child to last child position, and loop, creating a slideshow effect.
When I want this over i .empty() the container. Then the process can start again with the same or another object.
The first time I do this, it works, but second, third... times, it starts to glitch. Not only two, but all divs start to fade in and out, for I don't know what reason
This happens even if I am using the same object in the first, second, third... attempts.
It would seem as if although the divs are erased from DOM, apparently there is some memory of them? Could it be related to the fact that created divs share the name with previously created divs? maybe fadein out keep some kind of internal queue I am unaware of?
Here is an JsFiddle:
https://jsfiddle.net/93h51k9m/11/
and the code:
$(document).ready(function(){
var imgObject = {
imgs: ['http://lorempixel.com/400/200/sports/1/','http://lorempixel.com/400/200/sports/2/','http://lorempixel.com/400/200/sports/3/']
};
var imgObject2 = {
imgs: ['http://lorempixel.com/400/200/sports/4/','http://lorempixel.com/400/200/sports/5/','http://lorempixel.com/400/200/sports/6/']
};
var noImgObject = {
};
function prepare(index) {
if ($("#cover").css("display") != "none") {
console.log("cover is visible: hide it first");
console.log("fadeOut cover in 3000ms");
$("#cover").fadeOut(3000, function() {
console.log("then empty cover")
$("#cover").empty();
console.log("now for the images")
roll(index);
});
} else {
console.log("cover is already hidden: now for the images");
roll(index);
};
};
function roll(index) {
if (typeof index.imgs != "undefined") {
console.log("called object has images")
console.log("get them and their numbers")
var imgs = index.imgs;
var imgsLength = imgs.length;
console.log("create as many divs as imgs, and place each img as bg in each div")
for (i = 0; i < imgsLength; i++) {
$("#cover").append("<div class='imgdiv" + i + "'></div>");
$(".imgdiv" + i).css("background-image", "url('"+imgs[i]+"')");
};
console.log("now hide all but first div, fadeIn cover and start the carousel");
//as seen at http://snook.ca/archives/javascript/simplest-jquery-slideshow
$('#cover').fadeIn(3000);
$('#cover div:gt(0)').hide();
setInterval(function() {
console.log("fade and swap")
$('#cover :first-child').fadeOut(3000)
.next('div').fadeIn(3000)
.end().appendTo('#cover')
}, 6000);
} else {
console.log("index has no images, nothing to do");
};
};
$("#imgobj").click(function(){
console.log("imgObject called");
prepare(imgObject);
});
$("#imgobj2").click(function(){
console.log("imgObject2 called");
prepare(imgObject2);
});
$("#noimgobj").click(function(){
console.log("noImgObject called");
prepare(noImgObject);
});
});
Thank you
Every time click event is invoked, another interval is being started and that is the reason, actions are appended in the queue
Use global variable which will hold the setInterval instance and clear it every time you start new Interval.
var interval;
$(document).ready(function() {
var imgObject = {
imgs: ['http://lorempixel.com/400/200/sports/1/', 'http://lorempixel.com/400/200/sports/2/', 'http://lorempixel.com/400/200/sports/3/']
};
var imgObject2 = {
imgs: ['http://lorempixel.com/400/200/sports/4/', 'http://lorempixel.com/400/200/sports/5/', 'http://lorempixel.com/400/200/sports/6/']
};
var noImgObject = {};
function prepare(index) {
clearInterval(interval);
if ($("#cover").css("display") != "none") {
console.log("cover is visible: hide it first");
console.log("fadeOut cover in 3000ms");
$("#cover").fadeOut(3000, function() {
console.log("then empty cover")
$("#cover").empty();
console.log("now for the images")
roll(index);
});
} else {
console.log("cover is already hidden: now for the images");
roll(index);
};
};
function roll(index) {
if (typeof index.imgs != "undefined") {
console.log("called object has images")
console.log("get them and their numbers")
var imgs = index.imgs;
var imgsLength = imgs.length;
console.log("create as many divs as imgs, and place each img as bg in each div")
for (var i = 0; i < imgsLength; i++) {
$("#cover").append("<div class='imgdiv" + i + "'></div>");
$(".imgdiv" + i).css("background-image", "url('" + imgs[i] + "')");
};
console.log("now hide all but first div, fadeIn cover and start the carousel");
//as seen at http://snook.ca/archives/javascript/simplest-jquery-slideshow
$('#cover').fadeIn(3000);
$('#cover div:gt(0)').hide();
interval = setInterval(function() {
console.log("fade and swap")
$('#cover :first-child').fadeOut(3000)
.next('div').fadeIn(3000)
.end().appendTo('#cover')
}, 6000);
} else {
console.log("index has no images, nothing to do");
};
};
$("#imgobj").click(function() {
console.log("imgObject called");
prepare(imgObject);
});
$("#imgobj2").click(function() {
console.log("imgObject2 called");
prepare(imgObject2);
});
$("#noimgobj").click(function() {
console.log("noImgObject called");
prepare(noImgObject);
});
});
html {
color: black;
height: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
body {
height: 100%;
padding: 0;
margin: 0;
background: #f7fafa;
}
* {
box-sizing: border-box;
}
button {
cursor: pointer;
}
#buttons {
z-index: 1000;
}
#cover {
display: none;
position: fixed;
top: 5vh;
left: 0;
width: 100vw;
height: 95vh;
opacity: 0.5;
z-index: 0;
}
#cover div {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-repeat: no-repeat;
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="buttons">
<button id="imgobj">imgObject</button>
<button id="imgobj2">imgObject2</button>
<button id="noimgobj">noImgObject</button>
</div>
<div id="cover"></div>

Can't manage to close Coverpop popup

I'm using CoverPop to display a popup to my customers. Everything seems so easy but somehow I'm to dumb to make the popup closeable. I have inserted a "close" link, as described in the setup. However when I click on it, nothing happens.
Only way to close the popup is by pressing the escape key on my keyboard.
I know this must be ridiculous for some of you. I'd really appreciate some help though.
Thanks.
HTML
<script>
CoverPop.start({});
</script>
<div id="CoverPop-cover" class="splash">
<div class="CoverPop-content splash-center">
<h2 class="splash-title">Willkommen bei Exsys <span class="bold">Schweiz</span></h2>
<p class="splash-intro">Kunden aus Deutschland und anderen EU-Ländern wechseln bitte zu unserer <span class="bold">deutschen</span> Seite.</p>
<img src="{$ShopURL}/templates/xt_grid/img/shop-ch.png" title="EXSYS Online-Shop Schweiz" height="60" style="margin: 0 20px 0 0;" alt="Schweizer Exsys-Shop"/>
<img src="{$ShopURL}/templates/xt_grid/img/shop-de.png" height="60" alt="Shop Deutschland"/>
<p class="close-splash"><a class="CoverPop-close" href="#">Close</a></p>
</div><!--end .splash-center -->
</div><!--end .splash -->
CSS
.CoverPop-open,
.CoverPop-open body {
overflow: hidden;
}
#CoverPop-cover {
display: none;
position: fixed;
overflow-y: scroll;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1000;
-webkit-animation: fade-in .25s ease-in;
-moz-animation-name: fade-in .25s ease-in;
-ms-animation-name: fade-in .25s ease-in;
-o-animation-name: fade-in .25s ease-in;
animation-name: fade-in .25s ease-in;
}
.CoverPop-open #CoverPop-cover {
display: block;
}
.splash {
background-color:rgba(47, 99, 135, 0.9);
}
.splash-center {
background-color: white;
border-right: 8px solid #007ec8;
border-bottom: 8px solid #007ec8;
border-left: 8px solid #007ec8;
margin: 15px;
text-align: center;
top: 7px;
width: 15%;
}
.splash-center p{
margin: 20px 10px;
}
.splash-center h2{
font-size:16px;
width: 100%;
background:#007ec8;
padding: 10px 0;
color:#FFF;
}
JS
(function (CoverPop, undefined) {
'use strict';
// set default settings
var settings = {
// set default cover id
coverId: 'CoverPop-cover',
// duration (in days) before it pops up again
expires: 30,
// close if someone clicks an element with this class and prevent default action
closeClassNoDefault: 'CoverPop-close',
// close if someone clicks an element with this class and continue default action
closeClassDefault: 'CoverPop-close-go',
// change the cookie name
cookieName: '_ExsPop',
// on popup open function callback
onPopUpOpen: null,
// on popup close function callback
onPopUpClose: null,
// hash to append to url to force display of popup
forceHash: 'splash',
// hash to append to url to delay popup for 1 day
delayHash: 'go',
// close if the user clicks escape
closeOnEscape: true,
// set an optional delay (in milliseconds) before showing the popup
delay: 2000,
// automatically close the popup after a set amount of time (in milliseconds)
hideAfter: null
},
// grab the elements to be used
$el = {
html: document.getElementsByTagName('html')[0],
cover: document.getElementById(settings.coverId),
closeClassDefaultEls: document.querySelectorAll('.' + settings.closeClassDefault),
closeClassNoDefaultEls: document.querySelectorAll('.' + settings.closeClassNoDefault)
},
/**
* Helper methods
*/
util = {
hasClass: function(el, name) {
return new RegExp('(\\s|^)' + name + '(\\s|$)').test(el.className);
},
addClass: function(el, name) {
if (!util.hasClass(el, name)) {
el.className += (el.className ? ' ' : '') + name;
}
},
removeClass: function(el, name) {
if (util.hasClass(el, name)) {
el.className = el.className.replace(new RegExp('(\\s|^)' + name + '(\\s|$)'), ' ').replace(/^\s+|\s+$/g, '');
}
},
addListener: function(target, type, handler) {
if (target.addEventListener) {
target.addEventListener(type, handler, false);
} else if (target.attachEvent) {
target.attachEvent('on' + type, handler);
}
},
removeListener: function(target, type, handler) {
if (target.removeEventListener) {
target.removeEventListener(type, handler, false);
} else if (target.detachEvent) {
target.detachEvent('on' + type, handler);
}
},
isFunction: function(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
},
setCookie: function(name, days) {
var date = new Date();
date.setTime(+ date + (days * 86400000));
document.cookie = name + '=true; expires=' + date.toGMTString() + '; path=/';
},
hasCookie: function(name) {
if (document.cookie.indexOf(name) !== -1) {
return true;
}
return false;
},
// check if there is a hash in the url
hashExists: function(hash) {
if (window.location.hash.indexOf(hash) !== -1) {
return true;
}
return false;
},
preventDefault: function(event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
mergeObj: function(obj1, obj2) {
for (var attr in obj2) {
obj1[attr] = obj2[attr];
}
}
},
/**
* Private Methods
*/
// close popup when user hits escape button
onDocUp = function(e) {
if (settings.closeOnEscape) {
if (e.keyCode === 27) {
CoverPop.close();
}
}
},
openCallback = function() {
// if not the default setting
if (settings.onPopUpOpen !== null) {
// make sure the callback is a function
if (util.isFunction(settings.onPopUpOpen)) {
settings.onPopUpOpen.call();
} else {
throw new TypeError('CoverPop open callback must be a function.');
}
}
},
closeCallback = function() {
// if not the default setting
if (settings.onPopUpClose !== null) {
// make sure the callback is a function
if (util.isFunction(settings.onPopUpClose)) {
settings.onPopUpClose.call();
} else {
throw new TypeError('CoverPop close callback must be a function.');
}
}
};
/**
* Public methods
*/
CoverPop.open = function() {
var i, len;
if (util.hashExists(settings.delayHash)) {
util.setCookie(settings.cookieName, 1); // expire after 1 day
return;
}
util.addClass($el.html, 'CoverPop-open');
// bind close events and prevent default event
if ($el.closeClassNoDefaultEls.length > 0) {
for (i=0, len = $el.closeClassNoDefaultEls.length; i < len; i++) {
util.addListener($el.closeClassNoDefaultEls[i], 'click', function(e) {
if (e.target === this) {
util.preventDefault(e);
CoverPop.close();
}
});
}
}
// bind close events and continue with default event
if ($el.closeClassDefaultEls.length > 0) {
for (i=0, len = $el.closeClassDefaultEls.length; i < len; i++) {
util.addListener($el.closeClassDefaultEls[i], 'click', function(e) {
if (e.target === this) {
CoverPop.close();
}
});
}
}
// bind escape detection to document
util.addListener(document, 'keyup', onDocUp);
openCallback();
};
CoverPop.close = function(e) {
util.removeClass($el.html, 'CoverPop-open');
util.setCookie(settings.cookieName, settings.expires);
// unbind escape detection to document
util.removeListener(document, 'keyup', onDocUp);
closeCallback();
};
CoverPop.init = function(options) {
if (navigator.cookieEnabled) {
util.mergeObj(settings, options);
// check if there is a cookie or hash before proceeding
if (!util.hasCookie(settings.cookieName) || util.hashExists(settings.forceHash)) {
if (settings.delay === 0) {
CoverPop.open();
} else {
// delay showing the popup
setTimeout(CoverPop.open, settings.delay);
}
if (settings.hideAfter) {
// hide popup after the set amount of time
setTimeout(CoverPop.close, settings.hideAfter + settings.delay);
}
}
}
};
// alias
CoverPop.start = function(options) {
CoverPop.init(options);
};
}(window.CoverPop = window.CoverPop || {}));
Additional information
I quickly checked my site and these are the sections I found where the click event is present. Honestly I have no idea how they do interfere with the popup.
// tabs
$('ul.tabs').each(function(){
var $active, $content, $links = $(this).find('a');
$active = $links.first().addClass('active');
$content = $($active.attr('rel'));
$links.not(':first').each(function () {
$($(this).attr('rel')).hide();
});
$(this).on('click', 'a', function(e){
$active.removeClass('active');
$content.hide();
$active = $(this);
$content = $($(this).attr('rel'));
$active.addClass('active');
$content.show();
e.preventDefault();
});
});
// track box clicks and route them to parent radio button
$('div.box-hover').click( function(e)
{
$(this).find("input[type=radio]").click();
});
$('input[type=radio]').click(function(e){
if (this.checked != true && $(this).hasClass('autosubmit')){
this.checked = true;
this.form.submit();
}
e.stopPropagation();
});
// track box clicks to show/hide some desc (shipping/payment)
$('div.box-hover').click( function(e)
{
// ok. wir wollen clicks auf shipping abfangen
// und - laut tmpl - kann nur EIN passendes kind da sein
// also geht das mit dem length check!
if( $(this).children('p.shipping-name').length > 0)
{
$('div.box-hover').children('p.shipping-desc').css('display','none');
$(this).children('p.shipping-desc').css('display','block');
}
if( $(this).children('p.payment-name').length > 0)
{
$('div.box-hover').children('p.payment-desc').css('display','none');
$(this).children('p.payment-desc').css('display','block');
}
});
// autosize the comment textarea
$('#comments').autosize();
// slide in/out guest account form
$("#guest").click( function(e){
$("#cust_info_customers_password").val('');
$("#cust_info_customers_password_confirm").val('');
$('#guest-account').slideUp(250);
});
$("#account").click( function(e){
$('#guest-account').slideDown(250);
});
});
#santadani, found there is a rule to follow due to the implmentation of CoverPop itself. from your production environment, could you move the <script type="text/javascript" src="http://www.exsys.ch/templates/xt_grid/javascript/CoverPop.js"></script> to the end of document, before the </body> tag and try again?
It is because i saw in the CoverPop source, it grabs the element upon the script is loaded
$el = {
html: document.getElementsByTagName('html')[0],
cover: document.getElementById(settings.coverId),
closeClassDefaultEls: document.querySelectorAll('.' + settings.closeClassDefault),
closeClassNoDefaultEls: document.querySelectorAll('.' + settings.closeClassNoDefault)
},
which then the document.querySelectorAll('.' + settings.closeClassDefault) will retrieve nothing (becasue the script was loaded before the DOM are ready, therefore i suggest to try to move the script tag down)

Multiple instances of jQuery plugin on same page is not working

I have searched on this site but did not get what I need.
My issue is that I have created a jquery plugin for carousels, its working fine on 1 instance, but if I created multiple instance its only working on last.
ex:
$('#one').smartCarousel(); // its not working
$('#two').smartCarousel(); // its working
Here is the plugin code:
;(function($){
// default options
var defaults = {
slide : 1,
autoPlay : false,
autoPlayTime : 3000,
speed : 400,
next : false,
prev : false,
reverse : false,
show : 4
}
// function
function sc(el, o){
this.config = $.extend({}, defaults, o);
this.el = el;
this.init();
return this;
}
// set init configurations
sc.prototype.init = function(){
$this = this;
// get children
$this.children = $this.el.children();
// wrape element, add basic css properties
$this.el.wrap('<div class="smartCarouselWrapper clearfix"></div>')
.css({
position: 'absolute',
}).parent().css({
height: $this.el.outerHeight(true), // Height is setting on line 57
width: '100%',
overflow: 'hidden',
position: 'relative'
});
// Show element by config
// Calculate width by deviding wraper width
// Set width of items
$elw = $this.el.parent().width()/$this.config.show;
$this.children.each(function(index, el) {
$(this).width($elw);
});
w = $elw*$this.config.slide; // init width
// get width, hadle diffrent width
$this.children.each(function(index, el) {
w += $(this).outerWidth(true);
});
// set lement width
$this.el.width(w);
// Set height for wrapper
$this.el.parent().height($this.el.outerHeight(true));
// check if next handle assigned
if ($this.config.next != false ) {
$(this.config.next).click(function(e) {
e.preventDefault()
$this.next();
});
};
// check if prev handle assigned
if ($this.config.prev != false ) {
$(this.config.prev).click(function(e) {
e.preventDefault()
$this.prev();
});
};
$this.ready();
} // end of inti
sc.prototype.autoPlay = function(){
// if reverse enabled
if (this.config.reverse != false) { this.prev(); } else { this.next(); };
}
// do stuffs when ready
sc.prototype.ready = function(){
if(this.config.autoPlay != false){
this.timeOut = setTimeout('$this.autoPlay()', this.config.autoPlayTime);
}
}
sc.prototype.next = function(){
$this = this;
clearTimeout($this.timeOut);
l = 0; // left
i = 0; // index
// Add width to l from each element, limiting through slide
$this.children.each(function(index, el) {
if (i < $this.config.slide) {
l -= $(this).outerWidth(true);
//Clone first item after last for smooth animation
$this.el.append($this.children.eq(i).clone());
$this.children = $this.el.children();
};
i++;
});
// animat to show next items and appent prev items to end
$this.el.stop().animate({
left: l},
$this.config.speed, function() {
i = 0; // index
$this.children.each(function(index, el) {
if (i < $this.config.slide) {
$this.children.last().remove();
$this.children = $this.el.children();
};
i++;
});
i = 0;
$this.children.each(function(index, el) {
if (i < $this.config.slide) {
$(this).appendTo($this.el);
$this.el.css('left', parseInt($this.el.css('left'))+$(this).outerWidth(true));
};
i++;
});
$this.children = $this.el.children();
$this.ready();
});
} // end of next
sc.prototype.prev = function(){
$this = this;
clearTimeout($this.timeOut);
l = 0; // left
i = 0; // index
//move last item to first through slide
$this.children.each(function(index, el) {
if (i < $this.config.slide) {
//Clone first item after last for smooth animation
$this.el.prepend($this.children.eq(($this.children.length-1)-i).clone());
l -= $this.children.eq(($this.children.length-1)-i).outerWidth(true);
$this.el.css('left', l);
console.log(1);
};
i++;
});
console.log(l);
$this.children = $this.el.children();
// animate back to 0
$this.el.stop().animate({left: 0}, $this.config.speed, function(){
i = 0;
$this.children.each(function(index, el) {
if (i <= $this.config.slide) {
$this.children.eq($this.children.length-i).remove();
};
i++;
});
$this.children = $this.el.children();
$this.ready();
});
} // end of prev
// plugin
if (typeof $.smartCarousel != 'function') {
$.fn.smartCarousel = function(o){
if (this.length > 0) {
new sc(this.first(), o);
};
return this;
}
}else{
console.log('Function already declared.');
return this;
}
}(jQuery))
Here the html:
<ul class="smart-carousel-list clearfix" id="one">
<li><!-- Image here -->
<h3>Premium Quality DATES</h3>
</li>
<li><!-- Image here -->
<h3>Variety of Export Quality RICE</h3>
</li>
<li><!-- Image here -->
<h3>Sports Goods</h3>
</li>
<li><!-- Image here -->
<h3>Surgical Items</h3>
</li>
<li><!-- Image here -->
<h3>Bad Sheets</h3>
</li>
<li><!-- Image here -->
<h3>Towals</h3>
</li>
<li><!-- Image here -->
<h3>Fruits & Vegetable</h3>
</li>
</ul>
HERE IS THE CSS:
`
.smart-carousel{
width: 100%;
position: relative;
}
.smart-carousel-list{
list-style: none;
margin: 0;
padding: 0;
}
.smart-carousel-list li {
float: left;
-webkit-box-sizing: border-box !important; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box !important; /* Firefox, other Gecko */
box-sizing: border-box !important; /* Opera/IE 8+ */
}
.smart-carousel-nav{
position: absolute;
top: 0;
z-index: 1000;
opacity: 0;
transition: opacity 0.4s;
width: 100%;
}
.smart-carousel:hover .smart-carousel-nav{
opacity: 1;
}
.smart-carousel-nav a{
display: block;
width: 29px;
height: 28px;
text-indent: -999999px;
outline: none;
}
.smart-carousel-nav a.sc_next{
background-image: url('next.png');
margin-right: 10px;
float: right;
}
.smart-carousel-nav a.sc_prev{
background-image: url('prev.png');
margin-left: 10px;
float: left;
}
/**
* STYLE FOR TYPE : Images;
*/
.smart-carousel.type-images .smart-carousel-list li img{
max-width: 100%;
display: block;
margin: 0 auto;
}
/**
* STYLE FOR TYPE : Products;
*/
.smart-carousel.type-products .smart-carousel-list li{
border: solid 1px #efefef;
}
.smart-carousel.type-products .smart-carousel-list li img{
max-width: 100%;
display: block;
margin: 0 auto;
}
.smart-carousel.type-products .smart-carousel-list li h3{
width: 100%;
font-size: 18px;
margin: 0;
padding: 0;
}
.smart-carousel.type-products .smart-carousel-list li h3 a{
display: block;
padding: 10px;
font-weight: bold;
}
.smart-carousel.type-products .smart-carousel-list li h3 a span{
float: right;
font-weight: normal;
}
/**
* STYLE FOR TYPE : Posts;
*/
.smart-carousel.type-posts .smart-carousel-list li{
/*border: solid 1px #efefef;*/
}
.smart-carousel.type-posts .smart-carousel-list li img{
max-width: 100%;
display: block;
margin: 0 auto;
}
.smart-carousel.type-posts .smart-carousel-list li h3{
width: 100%;
font-size: 18px;
margin: 0;
padding: 0;
}
.smart-carousel.type-posts .smart-carousel-list li h3 a{
display: block;
padding: 10px;
font-weight: bold;
text-align: center;
}
.smart-carousel.type-posts .smart-carousel-list li h3 a span{
float: right;
font-weight: normal;
}
`
Your plugin is written to only connect to a single jQuery element at a time. You can improve that like this:
// plugin
if (typeof $.smartCarousel != 'function') {
$.fn.smartCarousel = function (o) {
this.each(function(){
// Connect to each jQuery element
new sc($(this), o);
});
return this;
}
} else {
console.log('Function already declared.');
return this;
}
As for the other problems, you have a single global $this shared all over the place. I added all the missing var $this where required for you and correctly reference it in the timer (via an anonymous function wrapper, so that I can reference the local $this):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/b7u4635x/4/
;
(function ($) {
// default options
var defaults = {
slide: 1,
autoPlay: true,
autoPlayTime: 1000,
speed: 400,
next: false,
prev: false,
reverse: false,
show: 4
}
// function
function sc(el, o) {
this.config = $.extend({}, defaults, o);
this.el = el;
this.init();
return this;
}
// set init configurations
sc.prototype.init = function () {
var $this = this;
// get children
$this.children = $this.el.children();
// wrape element, add basic css properties
$this.el.wrap('<div class="smartCarouselWrapper clearfix"></div>')
.css({
position: 'absolute',
}).parent().css({
height: $this.el.outerHeight(true), // Height is setting on line 57
width: '100%',
overflow: 'hidden',
position: 'relative'
});
// Show element by config
// Calculate width by deviding wraper width
// Set width of items
var $elw = $this.el.parent().width() / $this.config.show;
$this.children.each(function (index, el) {
$(this).width($elw);
});
var w = $elw * $this.config.slide; // init width
// get width, hadle diffrent width
$this.children.each(function (index, el) {
w += $(this).outerWidth(true);
});
// set lement width
$this.el.width(w);
// Set height for wrapper
$this.el.parent().height($this.el.outerHeight(true));
// check if next handle assigned
if ($this.config.next != false) {
$(this.config.next).click(function (e) {
e.preventDefault()
$this.next();
});
};
// check if prev handle assigned
if ($this.config.prev != false) {
$(this.config.prev).click(function (e) {
e.preventDefault()
$this.prev();
});
};
$this.ready();
} // end of inti
sc.prototype.autoPlay = function () {
var $this = this;
// if reverse enabled
if ($this.config.reverse != false) {
$this.prev();
} else {
$this.next();
};
}
// do stuffs when ready
sc.prototype.ready = function () {
var $this = this;
if ($this.config.autoPlay != false) {
$this.timeOut = setTimeout(function(){$this.autoPlay();}, $this.config.autoPlayTime);
}
}
sc.prototype.next = function () {
var $this = this;
clearTimeout($this.timeOut);
var l = 0; // left
var i = 0; // index
// Add width to l from each element, limiting through slide
$this.children.each(function (index, el) {
if (i < $this.config.slide) {
l -= $(this).outerWidth(true);
//Clone first item after last for smooth animation
$this.el.append($this.children.eq(i).clone());
$this.children = $this.el.children();
};
i++;
});
// animat to show next items and appent prev items to end
$this.el.stop().animate({
left: l
},
$this.config.speed, function () {
i = 0; // index
$this.children.each(function (index, el) {
if (i < $this.config.slide) {
$this.children.last().remove();
$this.children = $this.el.children();
};
i++;
});
i = 0;
$this.children.each(function (index, el) {
if (i < $this.config.slide) {
$(this).appendTo($this.el);
$this.el.css('left', parseInt($this.el.css('left')) + $(this).outerWidth(true));
};
i++;
});
$this.children = $this.el.children();
$this.ready();
});
} // end of next
sc.prototype.prev = function () {
var $this = this;
clearTimeout($this.timeOut);
var l = 0; // left
var i = 0; // index
//move last item to first through slide
$this.children.each(function (index, el) {
if (i < $this.config.slide) {
//Clone first item after last for smooth animation
$this.el.prepend($this.children.eq(($this.children.length - 1) - i).clone());
l -= $this.children.eq(($this.children.length - 1) - i).outerWidth(true);
$this.el.css('left', l);
console.log(1);
};
i++;
});
console.log(l);
$this.children = $this.el.children();
// animate back to 0
$this.el.stop().animate({
left: 0
}, $this.config.speed, function () {
i = 0;
$this.children.each(function (index, el) {
if (i <= $this.config.slide) {
$this.children.eq($this.children.length - i).remove();
};
i++;
});
$this.children = $this.el.children();
$this.ready();
});
} // end of prev
// plugin
if (typeof $.smartCarousel != 'function') {
$.fn.smartCarousel = function (o) {
this.each(function () {
new sc($(this), o);
});
return this;
}
} else {
console.log('Function already declared.');
return this;
}
}(jQuery));
//$('.smart-carousel-list').smartCarousel();
$('#one').smartCarousel();
$('#two').smartCarousel();
You have a global variable in your plugin, thus making it impossible for the plugin to work with more than one element because each call to the plugin will overwrite the $this for the previous instance to target the new element.
you simply need to add var in each location where it is missing.
var $this = this;
This will of course break any other place where you attempted to use a global $this (such as the setTimeout('$this.autoplay()',200), so you will need to re-write that portion of the code to not execute autoplay() in that way.

Categories