jquery Multiple text scroll on div hover not work - javascript

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>

Related

How to autogrow a textbox that has a variable font size

I am coding a website that lets you test typefaces and just like google fonts, the textarea in which you type should autogrow, when the user types in more text.
I tried this plugin by jaz303 and it works fine, if the font-size stays the same.
https://github.com/jaz303/jquery-grab-bag/blob/master/javascripts/jquery.autogrow-textarea.js
(function($) {
/**
* Auto-growing textareas; technique ripped from Facebook
*
*
* http://github.com/jaz303/jquery-grab-bag/tree/master/javascripts/jquery.autogrow-textarea.js
*/
$.fn.autogrow = function(options) {
return this.filter('textarea').each(function() {
var self = this;
var $self = $(self);
var minHeight = $self.height();
var noFlickerPad = $self.hasClass('autogrow-short') ? 0 : parseInt($self.css('lineHeight')) || 0;
var settings = $.extend({
preGrowCallback: null,
postGrowCallback: null
}, options);
var shadow = $('<div></div>').css({
position: 'absolute',
top: -10000,
left: -10000,
width: $self.width(),
fontSize: $self.css('fontSize'),
fontFamily: $self.css('fontFamily'),
fontWeight: $self.css('fontWeight'),
lineHeight: $self.css('lineHeight'),
resize: 'none',
'word-wrap': 'break-word'
}).appendTo(document.body);
var update = function(event) {
var times = function(string, number) {
for (var i = 0, r = ''; i < number; i++) r += string;
return r;
};
var val = self.value.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n$/, '<br/> ')
.replace(/\n/g, '<br/>')
.replace(/ {2,}/g, function(space) {
return times(' ', space.length - 1) + ' '
});
// Did enter get pressed? Resize in this keydown event so that the flicker doesn't occur.
if (event && event.data && event.data.event === 'keydown' && event.keyCode === 13) {
val += '<br />';
}
shadow.css('width', $self.width());
shadow.html(val + (noFlickerPad === 0 ? '...' : '')); // Append '...' to resize pre-emptively.
var newHeight = Math.max(shadow.height() + noFlickerPad, minHeight);
if (settings.preGrowCallback != null) {
newHeight = settings.preGrowCallback($self, shadow, newHeight, minHeight);
}
$self.height(newHeight);
if (settings.postGrowCallback != null) {
settings.postGrowCallback($self);
}
}
$self.change(update).keyup(update).keydown({
event: 'keydown'
}, update);
$(window).resize(update);
update();
});
};
However, I need the possibility for the user to change the font-size while testing and for some reason the autogrow doesn’t work anymore, as soon as I change the size.
Here is my Test jsFiddle:
http://jsfiddle.net/fquk6v3o/2/
The solution is to relaunch $("#autoGrowTextArea").autogrow(); when the slider value changes...
Sample code for doing this :
$("input[type='range']").change( function() {
$("#autoGrowTextArea").height("100px");
$("#autoGrowTextArea").autogrow();
});
New JSfiddle here : http://jsfiddle.net/newzy08/fquk6v3o/3/
You can achieve this with css as well using height and width in em units. Em means relative to the font-size of the element (2em means 2 times the size of the current font) w3schools.com/cssref/css_units.asp
I don't know if this works well together with the autogrowth plugin though.
$(document).ready(function(){
$("#font-small").click(function(){
$(".ta").css("font-size", "12px");
});
$("#font-big").click(function(){
$(".ta").css("font-size", "24px");
});
$("#font-huge").click(function(){
$(".ta").css("font-size", "36px");
});
});
.ta {
font-size: 12px;
height: 3em;
width: 10em;
resize: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<textarea class="ta">test</textarea>
</div>
<div>
<button id="font-small">fontsmall</button>
<button id="font-big">fontbig</button>
<button id="font-huge">fonthuge</button>
</div>

Highcharts Bar Chart not printing correctly

I have a bar chart using Highcharts. On the screen it looks like this:
But when I go to print it looks like this:
So basically nothing is showing up when I go to print. Here is the javascript I am using.
function qm_load_barcharts(qmsr_data) {
var bar_width = 200;
$('#profile-barchart tbody tr').each(function() {
$(this).children('td').eq(4).each(function() {
// Get the div id.
var $div_id = $(this).children('div').eq(0).attr('id');
// From the div id reconstitute the pfx in proper form.
var pfx = $div_id.replace(/^x/, '');
pfx = pfx.replace(/_/g, '.');
pfx = pfx.replace(/-/, '/');
// Look up our indicator values for the prefix.
var active_cnt = qmsr_data[pfx]['active'];
var latent_cnt = qmsr_data[pfx]['latent'];
var indicators_cnt = qmsr_data[pfx]['indicators'];
// Set our bar segment sizes.
var total = active_cnt + latent_cnt + indicators_cnt;
var active_size;
var latent_size;
var indicators_size;
if (active_cnt == 0) {
active_size = 0;
}
else {
active_size = Math.round((active_cnt/total) * bar_width);
}
if (latent_cnt == 0) {
latent_size = 0;
}
else {
latent_size = Math.round((latent_cnt/total) * bar_width);
}
if (indicators_cnt == 0) {
indicators_size = 0;
}
else {
indicators_size = Math.round((indicators_cnt/total) * bar_width);
}
if ((active_cnt + latent_cnt + indicators_cnt) == 0) {
// Perfect score, so make one full-width gray bar.
$('#' + $div_id).children('div.active-bar').eq(0).css("background-color", "#ababab");
$('#' + $div_id).children('div').eq(0).width(bar_width + 'px');
$('#' + $div_id).children('div').eq(1).width('0px');
$('#' + $div_id).children('div').eq(2).width('0px');
}
else {
// Set div sizes proportionately.
$('#' + $div_id).children('div').eq(0).width(active_size + 'px');
$('#' + $div_id).children('div').eq(1).width(latent_size + 'px');
$('#' + $div_id).children('div').eq(2).width(indicators_size + 'px');
// Set values inside dives.
$('#' + $div_id).children('div.active-bar').children('div').eq(0).html(active_cnt);
$('#' + $div_id).children('div.latent-bar').children('div').eq(0).html(latent_cnt);
$('#' + $div_id).children('div.indicators-bar').children('div').eq(0).html(indicators_cnt);
}
});
});
}
Here's the HTML:
<div id="<%= $pfx_id %>" class='qmsr-barchart'>
<div class='active-bar'>
<div class='hidden-nugget'></div>
</div>
<div class='latent-bar'>
<div class='hidden-nugget'></div>
</div>
<div class='indicators-bar'>
<div class='hidden-nugget'></div>
</div>
</div>
And here's the print view CSS:
#media print {
.active-bar {
background-color: #A74A44;
}
.latent-bar {
background-color: #EB8104;
}
.indicators-bar {
background-color: #E6E714;
}
}
I am trying to print it in Chrome, if that matters at all.

Slider with rslides rezising itself due to different size images

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

Ajax Code that loads images on click next and previous for any kind of image silder that has huge no of Images using jsp

I have one slider that works perfectly ..... but the images are loaded at the time of page load ...
I want to load the images on click because I have lot of images to display so I can't load it my homepage because the page takes time to load so I have to use Ajax that loads one image
and and append it to my list
can any body help me how to do it ...
here is the code .. its working ..
the java script part
(function($){
$.fn.imageSlider = function(options) {
var options = $.extend({
leftBtn: '.leftBtn',
rightBtn: '.rightBtn',
visible: 3,
autoPlay: false, // true or false
autoPlayDelay: 10 // delay in seconds
}, options);
var make = function() {
$(this).css('overflow', 'hidden');
var thisWidth = $(this).width();
var mod = thisWidth % options.visible;
if (mod) {
$(this).width(thisWidth - mod); // to prevent bugs while scrolling to the end of slider
}
var el = $(this).children('ul');
el.css({
position: 'relative',
left: '0'
});
var leftBtn = $(options.leftBtn), rightBtn = $(options.rightBtn);
var sliderFirst = el.children('li').slice(0, options.visible);
var tmp = '';
sliderFirst.each(function(){
tmp = tmp + '<li>' + $(this).html() + '</li>';
});
sliderFirst = tmp;
var sliderLast = el.children('li').slice(-options.visible);
tmp = '';
sliderLast.each(function(){
tmp = tmp + '<li>' + $(this).html() + '</li>';
});
sliderLast = tmp;
var elRealQuant = el.children('li').length;
el.append(sliderFirst);
el.prepend(sliderLast);
var elWidth = el.width()/options.visible;
el.children('li').css({
float: 'left',
width: elWidth
});
var elQuant = el.children('li').length;
el.width(elWidth * elQuant);
el.css('left', '-' + elWidth * options.visible + 'px');
function disableButtons() {
leftBtn.addClass('inactive');
rightBtn.addClass('inactive');
}
function enableButtons() {
leftBtn.removeClass('inactive');
rightBtn.removeClass('inactive');
}
leftBtn.click(function(event){
event.preventDefault();
if (!$(this).hasClass('inactive')) {
disableButtons();
el.animate({left: '+=' + elWidth + 'px'}, 400,
function(){
if ($(this).css('left') == '0px') {$(this).css('left', '-' + elWidth * elRealQuant + 'px');}
enableButtons();
}
);
}
return false;
});
rightBtn.click(function(event){
event.preventDefault();
if (!$(this).hasClass('inactive')) {
disableButtons();
el.animate({left: '-=' + elWidth + 'px'}, 400,
function(){
if ($(this).css('left') == '-' + (elWidth * (options.visible + elRealQuant)) + 'px') {$(this).css('left', '-' + elWidth * options.visible + 'px');}
enableButtons();
}
);
}
return false;
});
if (options.autoPlay) {
function aPlay() {
rightBtn.click();
delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
}
var delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
el.hover(
function() {
clearTimeout(delId);
},
function() {
delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
}
);
}
};
return this.each(make);
};
})(jQuery);
here is the html
<div class="slider-wrap">
<div class="slider">
<ul id="imgList" class="sliderList">
<li><img><src></li>
<li><img><src></li>
<li><img><src></li>
<li><img><src></li>
<li><img><src></li>
</ul>
</div>
<img src="/evfimages/prevLogo.png"/>
<img src="/evfimages/nextLogo.png"/>
This is the function that call Js File .
jQuery('.slider').imageSlider({
leftBtn: '.sa-left',
rightBtn: '.sa-right',
visible: 5,
});
And some CSS for formatting
So I have a large no of Images 500 .... so i want to use ajax that loads images on click and append to the current list of images ......
any link or suggestion will be appreciated ......

Passing data to custom console

I've been working on a little project and been trying to make my own debug console kinda thing, something that i can customize to what i need instead of using firebug.. so far i've got the two parts i need working but not togehter. I have a script that is going to report what the mouse enters and clicks on, it workded printing directly to the window DIV i have set up,, then yesterday ran across a JQuery console which i really liked, i cut out everything i didn't need and it works fine within its self, but not sure how to pass the data from my other method to that one,, i compiled the basic stuff to try to get it working... its probably something simple as ussual with me LOL and i could be confusing myself and making it harder then it needs to be
if anyone could help out that would be great
JsFiddle
after having a day off from work to sit down and actually mess with it for a while, reading Trip's comment LOL i decided to just go through the thing and clean it up as if it was working and took out a couple dozen un-needed functions and wrapped the main guts i was needing into one function that contained everything and made sure i wasn't using multiple variables to avoid conflict and some tweaking i got it to work.. so my conclusion from it there was to many functions leftover after i was deleting the stuff i didn't need. so heres the working code,, just incase someone is searching for something like this
JsFiddle
big thanks to Trip for point out all the Methods being used
function clock(){
var dayarray = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var montharray = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var suffix = "AM";
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var mydate = new Date();
var year = mydate.getFullYear();
var day = mydate.getDay();
var month = mydate.getMonth();
var daym = mydate.getDate();
if(hours >= 12){
suffix = "PM";
hours = hours - 12;
}
if(hours == 0){
hours = 12;
}
if(minutes < 10){
minutes = "0" + minutes
}
if(daym<10){
daym="0"+daym
}
//alert(hours);
return [hours, minutes, suffix, month, day, year, dayarray, montharray];
}
$('#consolex').click(function() { loadConsole(); });
var xD;
function loadConsole(){
if (document.forms[0].console.checked) {
// if CHECKED than LOAD Console
if (window.twd_console) {
window.twd_console.toggle();
} else {
function init($) {
function HistoryManager() {
this.curr = -1;
this.entries = [];
};
HistoryManager.prototype = {
push: function(item) {
if (this.entries.length && this.entries[0] == item) return;
if (item.match(/^\s*$/)) return;
this.entries.unshift(item);
this.curr = -1;
},
scroll: function(direction) {
var moveTo = this.curr + (direction == 'prev' ? 1 : -1);
if (moveTo >= 0 && moveTo < this.entries.length) {
this.curr = moveTo;
return this.entries[this.curr];
} else if (moveTo == -1) {
this.curr = moveTo;
return '';
} else {
return null;
}
}
};
var toolbar = 'hello';
var context = {},
history = new HistoryManager(),
$drag = $('<div/>').css({
backgroundColor: '#e0e0e0',
border: '1px solid #a0a0a0',
fontSize: '11px',
fontFamily: 'sans-serif',
lineHeight: 1,
padding: '5px',
marginBottom: '7px',
cursor: 'pointer',
textAlign: 'right'
}).html(toolbar),
$log = $('<div/>').css({
fontSize: '11px',
fontFamily: 'monospace',
color: 'white',
marginBottom: '7px',
height: '155px',
overflow: 'auto',
border: '1px solid #a0a0a0',
padding: '5px',
textAlign: 'left'
}),
$dummy = $('<div/>');
xD = function append(text, act, tag, id, color) {
var aX = ' » ', // Bullet
bX = '['+ clock()[0]+':'+clock()[1]+':'+clock()[2]+'] ', // Timestamp
cX = ' ERROR ', //ERROR
dX = ' Location ', //Location of ERROR
eX = ' ID Location ', //ID Location
fX = ' Cause '; //Cause of ERROR
$log.append($('<div/>').css({
'color': color || 'black',
margin: 0,
padding: 0
}).text(aX).append(bX).append(text).append(act).append(tag).append(id));
$log[0].scrollTop = $log[0].scrollHeight;
};
$(document).mousemove(function(evt) {
if (dragging) $container.css({
left: evt.pageX - dragging[0],
top: evt.pageY - dragging[1]
});
});
var pos = ($.browser.msie && $.browser.version < 7) ? 'absolute' : 'fixed';
var $container = $('<div/>').css({
backgroundColor: 'white',
padding: '7px',
position: pos,
opacity: 0.9,
top: '10px',
right: '10px',
width: '550px',
height: '200px',
border: '1px solid #000',
zIndex: 99999
}).appendTo(document.body);
$container.append($drag).append($log);
//xD('jQuery initialised!', 'green');
//xD('(using jQuery version ' + $.fn.jquery + ')');
//xD('jQuery initialised!', 'green');
//xD('(using jQuery version ' + $.fn.jquery + ')');
//xD('jQuery initialised!', 'green');
//xD('(using jQuery version ' + $.fn.jquery + ')');
//xD('jQuery initialised!', 'green');
//xD('(using jQuery version ' + $.fn.jquery + ')');
window.twd_console = $container;
};
if (typeof jQuery == 'undefined' || !jQuery.fn.jquery.match(/^1\.7/)) {
var e = document.createElement('script'),
jq = null;
e.onload = function() {
jq = jQuery;
jQuery.noConflict(true);
init(jq);
};
e.setAttribute('type', 'text/javascript');
e.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js');
document.body.appendChild(e);
} else {
init(jQuery);
}
}
} else if (!document.forms[0].console.checked) {
window.twd_console.hide();
}
mouse(true);
}
function mouse(bol){
var d = $("*", document.body);
if(bol){
// Cancel mousedown.
d.mousedown(function(event) {
var x = $(this).get(0),
y = x.tagName,
z = x.id;
switch (event.which) {
case 1:
//alert('Left mouse button click: ' + x.tagName);
xD(x.tagName, ' Left mouse button ',' '+ x.tagName+' ',' '+ x.id+' ', 'purple');
//xD(x.id, 'red');
break;
case 2:
//alert('Middle mouse button click: ' + x.tagName);
xD(x.tagName, ' Centermouse button ', x.tagName, x.id, 'purple');
break;
case 3:
//alert('Right mouse button click: ' + x.tagName);
xD(x.tagName, ' Right mouse button ', x.tagName, x.id, 'purple');
return null;
break;
default:
xD(x.tagName, ' mouse UNKNOWN ', x.tagName, x.id, 'purple');
}
});
// Transfer focus, if already open.
d.mouseenter(function(event) {
var x = $(this).get(0),
y = x.tagName,
z = x.id;
// $('#window').append('mouse entered' + x.tagName + '<br />');
try{
xD(y, ' Mouse Entered ', y, z, 'blue');
//xD(y, 'blue');
}catch(err){
alert(err);
}
});
}
};

Categories