Passing data to custom console - javascript

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);
}
});
}
};

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>

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 UI Slider - Change background color ONLY between handlers/sliders/markers

I am using jQuery UI Slider. I have multiple hanldes with range set to false. Is there a way to color the range between two handles/sliders/markers whatever you want to call them? I have not found a solution to this yet.
This is my code/initialization that I am using.
var initialValues = [180, 435, 1080, 1320],
updateValue = function (ui) {
var hours = Math.floor(ui.value / 60);
var minutes = ui.value - (hours * 60);
if (hours.length == 1) hours = '0' + hours;
if (minutes.length == 1) minutes = '0' + minutes;
if (minutes == 0) minutes = '00';
if (hours >= 12) {
if (hours == 12) {
hours = hours;
minutes = minutes + " PM";
} else {
hours = hours - 12;
minutes = minutes + " PM";
}
} else {
hours = hours;
minutes = minutes + " AM";
}
if (hours == 0) {
hours = 12;
minutes = minutes;
}
//console.log(ui.handle)
$(ui.handle).attr('data-value', hours + ':' + minutes);
};
var timeLabels = ["12:00 a.m","1:00 a.m","2:00 a.m","3:00 a.m","4:00 a.m","5:00 a.m","6:00 a.m","7:00 a.m","8:00 a.m","9:00 a.m","10:00 a.m","11:00 a.m",
"12:00 p.m","1:00 p.m","2:00 p.m","3:00 p.m","4:00 p.m","5:00 p.m","6:00 p.m","7:00 p.m","8:00 p.m","9:00 p.m","10:00 p.m","11:00 p.m", "12:00 p.m"];
(function ($) {
$.widget('my-namespace.customSlider', $.ui.slider, {
options: {
ticks: false
},
// Called when the slider is instantiated.
_create: function() {
// Call the orginal constructor, creating the slider normally.
this._super();
// If the "ticks" option is false or the "step" option is
// less than 5, there's nothing to do.
if ( !this.options.ticks || this.options.step < 5 ) {
return;
}
// Setup some variables for rendering the tick marks below the slider.
var cnt = this.options.min,
background = this.element.css( "border-color" ),
left;
while ( cnt <= this.options.max ) {
// Compute the "left" CSS property for the next tick mark.
left = ( cnt / this.options.max * 100 ).toFixed( 2 ) + "%";
// Creates the tick div, and adds it to the element. It adds the
// "ui-slider-tick" class, which has common properties for each tick.
// It also applies the computed CSS properties, "left" and "background".
//console.log($("</div>"))
$( "<div/>" ).addClass( "ui-slider-tick" )
.appendTo( this.element )
.css( { left: left, background: background } );
cnt += this.options.step;
}
console.log(this.element[0].id)
cnt = this.options.min
var i = 0;
while (cnt <= this.options.max) {
//console.log(timeLabels[i])
$($(".pct-slider#" + this.element[0].id).find('.ui-slider-tick')[cnt]).append("<div class='tick-labels'>" + timeLabels[i] + "</div>");
cnt = cnt + 4;
i++;
}
//$(".pct-slider#" + sliders[0]).find('.ui-slider-tick').find('.tick-labels').hide()
},
addValue: function( val ) {
this.options.values.push(val);
console.log(val)
var time = convertToTime(val)
console.log(time)
this._refresh();
$($(".ui-slider-handle").last()).attr('data-value', time)
},
removeValue: function( ) {
if (this.options.values.length > 1) {
this.options.values.pop( );
this._refresh();
}
}
});
})(jQuery);
var sliders =["mondaySlider", "tuesdaySlider","wednesdaySlider","thursdaySlider","fridaySlider","saturdaySlider","sundaySlider"];
$(".pct-slider#" + sliders[0])
.customSlider({
min: 0,
max: 1440,
step: 15,
range: false,
ticks: true,
values: initialValues,
create: function (event, ui) {
$.each( initialValues, function(i, v){
updateValue({
value: v,
handle: $(".pct-slider#" + sliders[0]).find('.ui-slider-handle').eq(i)
});
});
},
slide: function (event, ui) {
var handleIndex = $('a', event.target).index(ui.handle),
curr = ui.values[handleIndex],
next = ui.values[handleIndex + 1] - 15,
prev = ui.values[handleIndex - 1] + 15;
if (curr > next || curr < prev) {
return false;
}
updateValue(ui);
//positionSelects();
}
});
I was trying to append divs onto my handles, but when I append a div it makes my handle disappear. My thought was to append a div on two handles and color the background of that div. Not working out for me though.
Heres a fiddle of what my initial slider looks like : http://jsfiddle.net/5TTm4/3095/
I want to color between the sets of handles
You can add div inside your slider and resize them when you move the handles. With proper css it'll give the effect you're describing. You may need to tweak it a little bit, but this should give you some ideas:
HTML
//You add divs inside your slider, you need four, the last region will be
/background of slider
<div class="pct-slider" id="mondaySlider">
<div class="color-region"></div>
<div class="color-region"></div>
<div class="color-region"></div>
<div class="color-region"></div>
</div>
CSS
//Make your divs relative and give them color
.color-region
{
position: relative;
height: 100%;
float: left;
}
.color-region:nth-child(1)
{
background-color: blue;
}
.color-region:nth-child(1)
{
background-color: blue;
}
.color-region:nth-child(2)
{
background-color: red;
}
.color-region:nth-child(3)
{
background-color: yellow;
}
.color-region:nth-child(4)
{
background-color: green;
}
JS
function resize_colors() {
//you start at 0
var cur_pos = 0;
$(".ui-slider-handle").each(function (i) {
//for each handle you check position and set width of corresponding color div
$('.color-region').eq(i).css('width', $(this).position().left - cur_pos)
//update cur_pos to calculate next color width
cur_pos = $(this).position().left;
})
}
You'll see it doesn't follow completely on slide event, part of this is because slide event is triggered when it moves only, so when you stop, there's a moment not updating. But maybe if you run resize color on some other event it will give a better result.
See fiddle:http://jsfiddle.net/t4veqohy/1/

jQuery - this.option becomes undefined in load function

I'm trying to alter a Plugin a little bit, here's the Prototype function, I've marked what lines I've added.
OK, so my problem happens inside the img-load function I've added. I've surrounded the old code with one to assure that the script waits until the image has loaded.
The problem is, that "this" inside the load-function is not connected with the one outside. I've tried giving the load function a parameter but apparently it's not working or I'm doing something wrong.
Do you know an easy way to sort-of inherit "this"? I don'T really know what else to do.
Plugin.prototype._fade = function(number) {
var $element, currentSlide, next, slidesControl, value,
_this = this;
$element = $(this.element);
this.data = $.data(this);
if (!this.data.animating && number !== this.data.current + 1) {
$.data(this, "animating", true);
currentSlide = this.data.current;
if (number) {
number = number - 1;
value = number > currentSlide ? 1 : -1;
next = number;
} else {
value = this.data.direction === "next" ? 1 : -1;
next = currentSlide + value;
}
if (next === -1) {
next = this.data.total - 1;
}
if (next === this.data.total) {
next = 0;
}
this._setActive(next);
slidesControl = $(".slidesjs-control", $element);
var nxtImg = $(slidesControl.children(":eq(" + next + ")")).find("img:eq(0)"); // added
if ( nxtImg.attr("longdesc") !== undefined ) { // added
nxtImg.attr("src", nxtImg.attr("longdesc")); // added
nxtImg.removeAttr("longdesc"); // added
} // added
nxtImg.load(function(){ // added
slidesControl.children(":eq(" + next + ")").css({
display: "block",
left: 0,
zIndex: 0
});
this.options.callback.start(currentSlide + 1);
if (this.options.effect.fade.crossfade) {
return slidesControl.children(":eq(" + this.data.current + ")").stop().fadeOut(this.options.effect.fade.speed, (function() {
slidesControl.children(":eq(" + next + ")").css({
zIndex: 10
});
$.data(_this, "animating", false);
$.data(_this, "current", next);
return _this.options.callback.complete(next + 1);
}));
} else {
slidesControl.children(":eq(" + next + ")").css({
display: "none"
});
return slidesControl.children(":eq(" + currentSlide + ")").stop().fadeOut(this.options.effect.fade.speed, (function() {
slidesControl.children(":eq(" + next + ")").stop().fadeIn(_this.options.effect.fade.speed).css({
zIndex: 10
});
$.data(_this, "animating", false);
$.data(_this, "current", next);
return _this.options.callback.complete(next + 1);
}));
}
}); // added
}
};
You're capturing the this in a closure variable "_this". Isn't that working?

Can I create an HTML input field that stops accepting characters when it is "full"?

I would like to create HTML input fields (either single-line or textarea) that stop accepting new text when they are "full" - i.e. when there is no more room in the widget for new characters to be displayed.
This is different from a putting a maxlength limit on the number of characters, as (for example) 65 lowercase letter "i"s take up much less space than 65 uppercase "W"s in proportional fonts.
Is there a way to do this? (If there is, the solution would ideally also cover when text is pasted in, and truncate all the text over the limit).
Edit: The solution has to work with proportional fonts - maxlength does not help here, we are not interested in stopping at a character length.
The following uses the answer from https://stackoverflow.com/a/5047712/212869 to calculate the width of text, and I linked it to a textbox. Its really rough code :D but it does limit the textbox fairly well. The same principle could be used on a text area, but you would also have do it for both height and width.
http://jsfiddle.net/LMKtd/1/ - it outputs stuff to console so best to have it open if you have a look.
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('<div>' + this + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
$('#textinput').on('keyup', validatetext);
function validatetext(e) {
var w = parseInt(e.target.value.width());
if (w > 100) {
console.log("Width Gt 100px ["+w+"px] Char Count ["+e.target.value.length+"]");
do {
e.target.value = e.target.value.slice(0,-1);
} while (parseInt(e.target.value.width()) > 100)
} else {
console.log("Keep going! ["+w+"px] Char Count ["+e.target.value.length+"]");
}
}
Update
http://jsfiddle.net/LMKtd/8/
I've bodged together one for the text area too. It doesnt stop you going over the limits but it tells you when its too wide or tall. It's not very pretty :D
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('<div>' + this + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'visible', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
String.prototype.height = function(font) {
var f = font || '12px arial',
o = $('<div>' + this.replace(/[\r\n]/g,'<br />') + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.height();
o.remove();
return w;
}
$('#textinput').on('keyup', validatetext);
$('#areainput').keyup(validatearea);
function validatearea(e) {
var w = parseInt($(this).val().width());
var h = parseInt($(this).val().height());
var errw = false;
var errh = false;
if (h>100) {
errh = true
}
var lines = $(this).val().split(/[\r\n]/);
var errw = false;
for (var i = 0; i<lines.length; i++) {
if (parseInt(lines[i].width()) > 100) {
errw = true;
}
}
if ((errh == true) || (errw == true)) {
if ((errh == true) && (errw == false)) {
$('#areaerror').html("Too Tall, Width OK");
}
if ((errh == false) && (errw == true)) {
$('#areaerror').html("Height OK, Too Wide");
}
if ((errh == true) && (errw == true)) {
$('#areaerror').html("Too Tall, Too Wide");
}
} else {
$('#areaerror').html("Were Good");
}
}
function validatetext(e) {
var w = parseInt(e.target.value.width());
if (w > 100) {
console.log("Width Gt 100px ["+w+"px] Char Count ["+e.target.value.length+"]");
do {
e.target.value = e.target.value.slice(0,-1);
} while (parseInt(e.target.value.width()) > 100)
} else {
console.log("Keep going! ["+w+"px] Char Count ["+e.target.value.length+"]");
}
}
You can use the maxlength attribute
<input type="text" id="Textbox" name="Textbox" maxlength="10" />
How about jquery inputfit plugin ? check the demo and source
You might change the source to accommodate your requirements. Obviously you have to use jquery library an may not be suitable if you are searching for a solution in plain-JavaScript.
check the options (min size, max size) they seems fit for your requirement

Categories