jQuery + Get and Compare Element VALUE and ALT - javascript

I am trying to modify following script to do this check:
Check if input VALUE and ALT are the same.
If yes: empty VALUE
If no: keep VALUE
This is the script I am working on: (the part that i commented out, is where i tryed to figure out how to make the changes myself).
<script language="Javascript" type="text/javascript">
//<![CDATA[
jQuery.fn.placeholder = function(){
return this.each(function(){
var element = $(this)
var insertedNow =element.after("<span class='placeholder-spanbox'>"+ element.attr('alt')+ "</span>").attr("alt","").next('.placeholder-spanbox');
var leftOffset = (element.innerWidth() - element.width())/2+parseInt(element.css("border-left-width"));
var topOffset = ((element.innerHeight() - element.height())/2)+parseInt(element.css("border-top-width"));
var inputWidth = element.width();
var inputHeight = element.height();
var placeholderPos = inputHeight + topOffset + leftOffset;
insertedNow.css("padding-left",leftOffset+"px").css("padding-top",topOffset+"px").css("opacity",0.5).css("display","block").css("margin-top",-placeholderPos).css("cursor","text");
var objCSS = {'-webkit-transition':'opacity 100ms ease-in','-moz-transition':'opacity 100ms ease-in','-o-transition':'opacity 100ms ease-in','-ms-transition':'opacity 100ms ease-in','transition':'opacity 100ms ease-in','font-size':element.css('font-size'),'font-family':element.css('font-family'),'color':'#000000','font-weight':element.css('font-weight'),'width':element.css('width'),'float':element.css('float')};
insertedNow.css(objCSS);
//insertedNow.offset(element.offset());
element.bind("focus",updateSpanStatusFocus);
element.bind("keydown",updateSpanStatusKeyDown);
element.bind("keyup",updateSpanStatusKeyUp);
element.bind("blur",updateSpanStatusBlur);
insertedNow.bind("click",clickSpanBox);
var inputVal = element.attr("value");
var inputAlt = element.attr("alt");
//$(this).attr("value",+inputVal);
// if(inputVal == inputAlt){
// $(this).attr("value","123");
// }
if(element.val()!==""){
insertedNow.css({'opacity':0});
}
});
function clickSpanBox(event){
event.preventDefault();
var inputBox = $(this).prev();
inputBox.focus();
}
function updateSpanStatusFocus(event){
var $this= $(this);
if($this.val()==""){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0.3");
}
}
function updateSpanStatusKeyUp(event){
var $this= $(this);
if($this.val()==""){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0.3");
}
}
function updateSpanStatusKeyDown(event){
var $this = $(this);
if($this.val()=="" && (event.keyCode>54 || event.keyCode == 32)){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0");
}
}
function updateSpanStatusBlur(){
var $this= $(this);
$this.val(Trim($this.val()+''));
if($this.val()==""){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0.5");
spanBox.css("color","#000000");
}
}
}
$(document).ready(function(){
$('.spanOverlay').placeholder();
});
//]]>
</script>
And here the html markup example:
<input type='text' name="userName" class='contactInput spanOverlay' alt='* Name' value='test'></input>
Thanks for your help!!

Is this what you want?
if (element.val() == element.attr('alt')) {
element.val("");
}

there's something called .defaultValue in javascript u could use this to compare against current value
here's an example on how its done
http://www.miuaiga.com/index.cfm/2009/8/31/jQuery-form-input-defaultValue

Related

jQuery click(function(event) hyperlinks won't work

I can't figure out why the hyperlinks wont work when using a jQuery click event.
I would like 1 button to work as a link
and one as a jump to in the current page.
div class="shortcat">
<i class="icon-thumbs-up"></i>Test Now
<i class="icon-picture"></i>Learn More
</div>
//--------- jQuery ---------------//
jQuery(window).load(function() {
jQuery("#loaderInner").fadeOut();
jQuery("#loader").delay(400).fadeOut("slow");
$('.teaserTitle ').stop().animate({marginTop :'330px', opacity:"1"}, 1000, 'easeOutQuint');
$('.shortcat a ').stop().animate({marginTop :'65px', opacity:"1"}, 600, 'easeOutQuint');
});
$(document).ready(function(){
$("#mainNav ul a, .logo a, .shortcat a, .notBtn a").click(function(event){
event.preventDefault();
var full_url = this.href;
var parts = full_url.split("#");
var trgt = parts[1];
var target_offset = $("#"+trgt).offset();
var target_top = target_offset.top;
$('html,body').animate({scrollTop:target_top -80}, 800);
});
//-------------Highlight the current section in the navigation bar------------//
var sections = $("section");
var navigation_links = $("#mainNav a");
sections.waypoint({
handler: function(event, direction) {
var active_section;
active_section = $(this);
if (direction === "up") active_section = active_section.prev();
var active_link = $('#mainNav a[href="#' + active_section.attr("id") + '"]');
navigation_links.removeClass("active");
active_link.addClass("active");
},
offset: '35%'
});
First part is the HTML the second part is my script.js
I think the click function event is wrong.
When i remove the shortcut out of it the hyperlink will work but the jump to not anymore.
Will there be an easy fix?
here you go: this works well
http://jsfiddle.net/6g4j2/
$(document).ready(function(){
$("#mainNav ul a, .logo a, .shortcat a, .notBtn a").click(function(event){
var full_url = this.href;
var parts = full_url.split("#");
var trgt = parts[1];
if (trgt != undefined) {
event.preventDefault();
var target_offset = $("#"+trgt).offset();
var target_top = target_offset.top;
$('html,body').animate({scrollTop:target_top -80}, 800);
return false;
}
});
});
most likely the function from the click event fails here
var trgt = parts[1];
for the first link, because parts will be undefined

setInterval won't get out of loop

The following javascript code takes randomly selected value from a array and types it in the input box. I've used jquery. I want to end setInterval "zaman2", so after It ends I can retype the next random string to the input box. But the loop doesn't end and gets stuck. How can I solve this?
Link to jsFiddle: http://jsfiddle.net/AQbq4/4/
var dersler = [...very long list...];
var zaman = setTimeout(function() {
var yeniDers = dersler[Math.floor(Math.random()*dersler.length)];
sayac = 0;
var zaman2 = setInterval(function() {
var harf = yeniDers.slice(0,(sayac+1));
sayac++;
$('#main-search').attr('placeholder', harf).typeahead({source: dersler});
if (sayac == yeniDers.length) {
clearInterval(zaman2);
}
},450);
},2000);
Don't you mean
DEMO
var tId, tId2;
function show() {
var ran = arr[Math.floor(Math.random()*arr.length)];
cnt = 0;
tId = setInterval(function() {
var char = ran.slice(0,(cnt+1));
cnt++;
$( '#main-search' ).attr('placeholder', char);
if (cnt == ran.length) {
clearInterval(tId);
tId2=setTimeout(show,2000);
}
},450);
}
show();

How to dynamically add elements via jQuery

The script below creates a slider widget the takes a definition list and turns it into a slide deck. Each dt element is rotated via css to become the "spine", which is used to reveal that dt's sibling dd element.
What I'm trying to do is to enhance it so that I can have the option to remove the spines from the layout and just use forward and back buttons on either side of the slide deck. To do that, I set the dt's to display:none via CSS and use the code under the "Remove spine layout" comment to test for visible.
This works fine to remove the spines, now I need to dynamically create 2 absolutely positioned divs to hold the left and right arrow images, as well as attach a click handler to them.
My first problem is that my attempt to create the divs is not working.
Any help much appreciated.
jQuery.noConflict();
(function(jQuery) {
if (typeof jQuery == 'undefined') return;
jQuery.fn.easyAccordion = function(options) {
var defaults = {
slideNum: true,
autoStart: false,
pauseOnHover: true,
slideInterval: 5000
};
this.each(function() {
var settings = jQuery.extend(defaults, options);
jQuery(this).find('dl').addClass('easy-accordion');
// -------- Set the variables ------------------------------------------------------------------------------
jQuery.fn.setVariables = function() {
dlWidth = jQuery(this).width()-1;
dlHeight = jQuery(this).height();
if (!jQuery(this).find('dt').is(':visible')){
dtWidth = 0;
dtHeight = 0;
slideTotal = 0;
// Add an element to rewind to previous slide
var slidePrev = document.createElement('div');
slidePrev.className = 'slideAdv prev';
jQuery(this).append(slidePrev);
jQuery('.slideAdv.prev').css('background':'red','width':'50px','height':'50px');
// Add an element to advance to the next slide
var slideNext = document.createElement('div');
slideNext.className = 'slideAdv next';
jQuery(this).append(slideNext);
jQuery('.slideAdv.next').css('background':'green','width':'50px','height':'50px');
}
else
{
dtWidth = jQuery(this).find('dt').outerHeight();
if (jQuery.browser.msie){ dtWidth = jQuery(this).find('dt').outerWidth();}
dtHeight = dlHeight - (jQuery(this).find('dt').outerWidth()-jQuery(this).find('dt').width());
slideTotal = jQuery(this).find('dt').size();
}
ddWidth = dlWidth - (dtWidth*slideTotal) - (jQuery(this).find('dd').outerWidth(true)-jQuery(this).find('dd').width());
ddHeight = dlHeight - (jQuery(this).find('dd').outerHeight(true)-jQuery(this).find('dd').height());
};
jQuery(this).setVariables();
// -------- Fix some weird cross-browser issues due to the CSS rotation -------------------------------------
if (jQuery.browser.safari){ var dtTop = (dlHeight-dtWidth)/2; var dtOffset = -dtTop; /* Safari and Chrome */ }
if (jQuery.browser.mozilla){ var dtTop = dlHeight - 20; var dtOffset = - 20; /* FF */ }
if (jQuery.browser.msie){ var dtTop = 0; var dtOffset = 0; /* IE */ }
if (jQuery.browser.opera){ var dtTop = (dlHeight-dtWidth)/2; var dtOffset = -dtTop; } /* Opera */
// -------- Getting things ready ------------------------------------------------------------------------------
var f = 1;
var paused = false;
jQuery(this).find('dt').each(function(){
jQuery(this).css({'width':dtHeight,'top':dtTop,'margin-left':dtOffset});
// add unique id to each tab
jQuery(this).addClass('spine_' + f);
// add active corner
var corner = document.createElement('div');
corner.className = 'activeCorner spine_' + f;
jQuery(this).append(corner);
if(settings.slideNum == true){
jQuery('<span class="slide-number">'+f+'</span>').appendTo(this);
if(jQuery.browser.msie){
var slideNumLeft = parseInt(jQuery(this).find('.slide-number').css('left'));
if(jQuery.browser.version == 6.0 || jQuery.browser.version == 7.0){
jQuery(this).find('.slide-number').css({'bottom':'auto'});
slideNumLeft = slideNumLeft - 14;
jQuery(this).find('.slide-number').css({'left': slideNumLeft})
}
if(jQuery.browser.version == 8.0 || jQuery.browser.version == 9.0){
var slideNumTop = jQuery(this).find('.slide-number').css('bottom');
var slideNumTopVal = parseInt(slideNumTop) + parseInt(jQuery(this).css('padding-top')) - 20;
jQuery(this).find('.slide-number').css({'bottom': slideNumTopVal});
slideNumLeft = slideNumLeft - 10;
jQuery(this).find('.slide-number').css({'left': slideNumLeft})
jQuery(this).find('.slide-number').css({'marginTop': 10});
}
} else {
var slideNumTop = jQuery(this).find('.slide-number').css('bottom');
var slideNumTopVal = parseInt(slideNumTop) + parseInt(jQuery(this).css('padding-top'));
jQuery(this).find('.slide-number').css({'bottom': slideNumTopVal});
}
}
f = f + 1;
});
if(jQuery(this).find('.active').size()) {
jQuery(this).find('.active').next('dd').addClass('active');
} else {
jQuery(this).find('dt:first').addClass('active').next('dd').addClass('active');
}
jQuery(this).find('dt:first').css({'left':'0'}).next().css({'left':dtWidth});
jQuery(this).find('dd').css({'width':ddWidth,'height':ddHeight});
// -------- Functions ------------------------------------------------------------------------------
jQuery.fn.findActiveSlide = function() {
var i = 1;
this.find('dt').each(function(){
if(jQuery(this).hasClass('active')){
activeID = i; // Active slide
} else if (jQuery(this).hasClass('no-more-active')){
noMoreActiveID = i; // No more active slide
}
i = i + 1;
});
};
jQuery.fn.calculateSlidePos = function() {
var u = 2;
jQuery(this).find('dt').not(':first').each(function(){
var activeDtPos = dtWidth*activeID;
if(u <= activeID){
var leftDtPos = dtWidth*(u-1);
jQuery(this).animate({'left': leftDtPos});
if(u < activeID){ // If the item sits to the left of the active element
jQuery(this).next().css({'left':leftDtPos+dtWidth});
} else{ // If the item is the active one
jQuery(this).next().animate({'left':activeDtPos});
}
} else {
var rightDtPos = dlWidth-(dtWidth*(slideTotal-u+1));
jQuery(this).animate({'left': rightDtPos});
var rightDdPos = rightDtPos+dtWidth;
jQuery(this).next().animate({'left':rightDdPos});
}
u = u+ 1;
});
setTimeout( function() {
jQuery('.easy-accordion').find('dd').not('.active').each(function(){
jQuery(this).css({'display':'none'});
});
}, 400);
};
jQuery.fn.activateSlide = function() {
this.parent('dl').setVariables();
this.parent('dl').find('dd').css({'display':'block'});
this.parent('dl').find('dd.plus').removeClass('plus');
this.parent('dl').find('.no-more-active').removeClass('no-more-active');
this.parent('dl').find('.active').removeClass('active').addClass('no-more-active');
this.addClass('active').next().addClass('active');
this.parent('dl').findActiveSlide();
if(activeID < noMoreActiveID){
this.parent('dl').find('dd.no-more-active').addClass('plus');
}
this.parent('dl').calculateSlidePos();
};
jQuery.fn.rotateSlides = function(slideInterval, timerInstance) {
var accordianInstance = jQuery(this);
timerInstance.value = setTimeout(function(){accordianInstance.rotateSlides(slideInterval, timerInstance);}, slideInterval);
if (paused == false){
jQuery(this).findActiveSlide();
var totalSlides = jQuery(this).find('dt').size();
var activeSlide = activeID;
var newSlide = activeSlide + 1;
if (newSlide > totalSlides) {newSlide = 1; paused = true;}
jQuery(this).find('dt:eq(' + (newSlide-1) + ')').activateSlide(); // activate the new slide
}
}
// -------- Let's do it! ------------------------------------------------------------------------------
function trackerObject() {this.value = null}
var timerInstance = new trackerObject();
jQuery(this).findActiveSlide();
jQuery(this).calculateSlidePos();
if (settings.autoStart == true){
var accordianInstance = jQuery(this);
var interval = parseInt(settings.slideInterval);
timerInstance.value = setTimeout(function(){
accordianInstance.rotateSlides(interval, timerInstance);
}, interval);
}
jQuery(this).find('dt').not('active').click(function(){
var accordianInstance = jQuery(this); //JSB to fix bug with IE < 9
jQuery(this).activateSlide();
clearTimeout(timerInstance.value);
timerInstance.value = setTimeout(function(){
accordianInstance.rotateSlides(interval, timerInstance);
}, interval);
});
if (!(jQuery.browser.msie && jQuery.browser.version == 6.0)){
jQuery('dt').hover(function(){
jQuery(this).addClass('hover');
}, function(){
jQuery(this).removeClass('hover');
});
}
if (settings.pauseOnHover == true){
jQuery('dd').hover(function(){
paused = true;
}, function(){
paused = false;
});
}
});
};
})(jQuery);
Creating elements in jQuery is easy:
$newDiv = $('<div />');
$newDiv.css({
'position': 'absolute',
'top': '10px',
'left': '10px'
});
$newDiv.on('click', function() {
alert('You have clicked me');
});
$('#your_container').append($newDiv);

jQuery password generator

I have the following JS code that checks a password strength and also creates a random password as well. What I want to do is edit the code so that instead of putting the generated password inside the password field it will put it inside a span tag with say an id of randompassword. In addition that I would like it so that by default there will be a random password inside the span tag and then when the user clicks the button it will generate another one. And also move the link to be next to span tag rather than the password box.
Thanks.
Here is the code:
$.fn.passwordStrength = function( options ){
return this.each(function(){
var that = this;that.opts = {};
that.opts = $.extend({}, $.fn.passwordStrength.defaults, options);
that.div = $(that.opts.targetDiv);
that.defaultClass = that.div.attr('class');
that.percents = (that.opts.classes.length) ? 100 / that.opts.classes.length : 100;
v = $(this)
.keyup(function(){
if( typeof el == "undefined" )
this.el = $(this);
var s = getPasswordStrength (this.value);
var p = this.percents;
var t = Math.floor( s / p );
if( 100 <= s )
t = this.opts.classes.length - 1;
this.div
.removeAttr('class')
.addClass( this.defaultClass )
.addClass( this.opts.classes[ t ] );
})
.after('Generate Password')
.next()
.click(function(){
$(this).prev().val( randomPassword() ).trigger('keyup');
return false;
});
});
function getPasswordStrength(H){
var D=(H.length);
if(D>5){
D=5
}
var F=H.replace(/[0-9]/g,"");
var G=(H.length-F.length);
if(G>3){G=3}
var A=H.replace(/\W/g,"");
var C=(H.length-A.length);
if(C>3){C=3}
var B=H.replace(/[A-Z]/g,"");
var I=(H.length-B.length);
if(I>3){I=3}
var E=((D*10)-20)+(G*10)+(C*15)+(I*10);
if(E<0){E=0}
if(E>100){E=100}
return E
}
function randomPassword() {
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$_+?%^&)";
var size = 10;
var i = 1;
var ret = ""
while ( i <= size ) {
$max = chars.length-1;
$num = Math.floor(Math.random()*$max);
$temp = chars.substr($num, 1);
ret += $temp;
i++;
}
return ret;
}
};
$(document)
.ready(function(){
$('#password1').passwordStrength({targetDiv: '#iSM',classes : Array('weak','medium','strong')});
});
// you can use another improved version to generate password as follows
//Define
function wpiGenerateRandomNumber(length) {
var i = 0;
var numkey = "";
var randomNumber;
while( i < length) {
randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
if ((randomNumber >=58) && (randomNumber <=90)) { continue; }
if ((randomNumber >=91) && (randomNumber <=122)) { continue; }
if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
i++;
numkey += String.fromCharCode(randomNumber);
}
return numkey;
}
// Call
var myKey=wpiGenerateRandomNumber(10); // 10=length
alert(myKey);
// Output
2606923083
This line:
$(this).prev().val( randomPassword() ).trigger('keyup');
is inserting the value after a click. So you can change that value to stick the password wherever you want it. For example you could change it to:
$('span#randompassword').html(randomPassword());
You could also run this when the page loads to stick something in that span right away:
$(document).ready(function(){
$('span#randompassword').html(randomPassword());
});
//Very simple method to generate random number; can be use to generate random password key as well
jq(document).ready( function() {
jq("#genCodeLnk").click( function() {
d = new Date();
t = d.getTime();
jq("#cstm_invitecode").val(t);
});
});

jqtransform form events problem

I'm a web designer with css experience, but I'm not a JS developer.
I used jqtransform to style a search form ,
the problem is it removes all events from selectors and the search button .
here is the code before jqtransform
<input id="go-search" type="button" name="btn_search" value="search" onclick="searchLocations()" />
and after applying the script, the button doesn't do any thing
I opened the page source and here how it looks like:
<button class=" jqTransformButton" type="button" name="btn_search" id="go-search"><span><span>search</span></span></button>
Please help me !
I think it’s best to put new questions in new posts …
$(function() { $("form.jqtransform").jqTransform(); $("#city").click(populateDestrict); });
when assigning functions to an event by JavaScript, you only assign the function reference. putting parentheses behind a function identifyer will execute the function.
function myFunction(x)
{
alert(x);
return 1;
}
// correct, the onload event will trigger the function
window.onload = myFunction;
// alerts "[object Event]"
// wrong
window.onload = myFunction("hello");
// this assigns "1" to the onload property*
// * - IE may execute this, but no standard compliant browser
As far as can see only buttons are affected. The script replaces your original buttons with new ones, so everything besides the id, name, type & class attributes is removed. You would have to assign the function anew when jqtransform finished its job.
// after jqtransform
// probably $("#go-search").click(searchLocations); in jQuery, but I’m not a jQuery user … thus in plain JavaScript:
var bt = document.getElementById("go-search");
if (window.addEventListener) {
bt.addEventListener("click", searchLocations, false);
}
else {
bt.attachEvent("onclick", searchLocations);
}
I would hazard a guess at using it like
$(function() {
//find all form with class jqtransform and apply the plugin
$("form.jqtransform").jqTransform();
// fix your button
$("#go-search").click(searchLocations);
});
May be late but... Faced the same issue recently. and the solution was to use this version of the jqTransform script:
NOTE: 1) Open your jqTransform file, 2)DELETE everything, 3)COPY the code bellow 4) PASTE and 5) SAVE.
VOILA!!
/*
*
* jqTransform
* by mathieu vilaplana mvilaplana#dfc-e.com
* Designer ghyslain armand garmand#dfc-e.com
*
*
* Version 1.0 25.09.08
* Version 1.1 06.08.09
* Add event click on Checkbox and Radio
* Auto calculate the size of a select element
* Can now, disabled the elements
* Correct bug in ff if click on select (overflow=hidden)
* No need any more preloading !!
*
******************************************** */
(function($){
var defaultOptions = {preloadImg:true};
var jqTransformImgPreloaded = false;
var jqTransformPreloadHoverFocusImg = function(strImgUrl) {
//guillemets to remove for ie
strImgUrl = strImgUrl.replace(/^url\((.*)\)/,'$1').replace(/^\"(.*)\"$/,'$1');
var imgHover = new Image();
imgHover.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-hover.$1');
var imgFocus = new Image();
imgFocus.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-focus.$1');
};
/***************************
Labels
***************************/
var jqTransformGetLabel = function(objfield){
var selfForm = $(objfield.get(0).form);
var oLabel = objfield.next();
if(!oLabel.is('label')) {
oLabel = objfield.prev();
if(oLabel.is('label')){
var inputname = objfield.attr('id');
if(inputname){
oLabel = selfForm.find('label[for="'+inputname+'"]');
}
}
}
if(oLabel.is('label')){return oLabel.css('cursor','pointer');}
return false;
};
/* Hide all open selects */
var jqTransformHideSelect = function(oTarget){
var ulVisible = $('.jqTransformSelectWrapper ul:visible');
ulVisible.each(function(){
var oSelect = $(this).parents(".jqTransformSelectWrapper:first").find("select").get(0);
//do not hide if click on the label object associated to the select
if( !(oTarget && oSelect.oLabel && oSelect.oLabel.get(0) == oTarget.get(0)) ){$(this).hide();}
});
};
/* Check for an external click */
var jqTransformCheckExternalClick = function(event) {
if ($(event.target).parents('.jqTransformSelectWrapper').length === 0) { jqTransformHideSelect($(event.target)); }
};
/* Apply document listener */
var jqTransformAddDocumentListener = function (){
$(document).mousedown(jqTransformCheckExternalClick);
};
/* Add a new handler for the reset action */
var jqTransformReset = function(f){
var sel;
$('.jqTransformSelectWrapper select', f).each(function(){sel = (this.selectedIndex<0) ? 0 : this.selectedIndex; $('ul', $(this).parent()).each(function(){$('a:eq('+ sel +')', this).click();});});
$('a.jqTransformCheckbox, a.jqTransformRadio', f).removeClass('jqTransformChecked');
$('input:checkbox, input:radio', f).each(function(){if(this.checked){$('a', $(this).parent()).addClass('jqTransformChecked');}});
};
/***************************
Buttons
***************************/
$.fn.jqTransInputButton = function(){
return this.each(function(){
var newBtn = $('<button id="'+ this.id +'" name="'+ this.name +'" type="'+ this.type +'" class="'+ this.className +' jqTransformButton"><span><span>'+ $(this).attr('value') +'</span></span>')
.hover(function(){newBtn.addClass('jqTransformButton_hover');},function(){newBtn.removeClass('jqTransformButton_hover')})
.mousedown(function(){newBtn.addClass('jqTransformButton_click')})
.mouseup(function(){newBtn.removeClass('jqTransformButton_click')})
;
$(this).replaceWith(newBtn);
});
};
/***************************
Text Fields
***************************/
$.fn.jqTransInputText = function(){
return this.each(function(){
var $input = $(this);
if($input.hasClass('jqtranformdone') || !$input.is('input')) {return;}
$input.addClass('jqtranformdone');
var oLabel = jqTransformGetLabel($(this));
oLabel && oLabel.bind('click',function(){$input.focus();});
var inputSize=$input.width();
if($input.attr('size')){
inputSize = $input.attr('size')*10;
$input.css('width',inputSize);
}
$input.addClass("jqTransformInput").wrap('<div class="jqTransformInputWrapper"><div class="jqTransformInputInner"><div></div></div></div>');
var $wrapper = $input.parent().parent().parent();
$wrapper.css("width", inputSize+10);
$input
.focus(function(){$wrapper.addClass("jqTransformInputWrapper_focus");})
.blur(function(){$wrapper.removeClass("jqTransformInputWrapper_focus");})
.hover(function(){$wrapper.addClass("jqTransformInputWrapper_hover");},function(){$wrapper.removeClass("jqTransformInputWrapper_hover");})
;
/* If this is safari we need to add an extra class */
$.browser.safari && $wrapper.addClass('jqTransformSafari');
$.browser.safari && $input.css('width',$wrapper.width()+16);
this.wrapper = $wrapper;
});
};
/***************************
Check Boxes
***************************/
$.fn.jqTransCheckBox = function(){
return this.each(function(){
if($(this).hasClass('jqTransformHidden')) {return;}
var $input = $(this);
var inputSelf = this;
//set the click on the label
var oLabel=jqTransformGetLabel($input);
oLabel && oLabel.click(function(){aLink.trigger('click');});
var aLink = $('');
//wrap and add the link
$input.addClass('jqTransformHidden').wrap('<span class="jqTransformCheckboxWrapper"></span>').parent().prepend(aLink);
//on change, change the class of the link
$input.change(function(){
this.checked && aLink.addClass('jqTransformChecked') || aLink.removeClass('jqTransformChecked');
return true;
});
// Click Handler, trigger the click and change event on the input
aLink.click(function(){
//do nothing if the original input is disabled
if($input.attr('disabled')){return false;}
//trigger the envents on the input object
$input.trigger('click').trigger("change");
return false;
});
// set the default state
this.checked && aLink.addClass('jqTransformChecked');
});
};
/***************************
Radio Buttons
***************************/
$.fn.jqTransRadio = function(){
return this.each(function(){
if($(this).hasClass('jqTransformHidden')) {return;}
var $input = $(this);
var inputSelf = this;
oLabel = jqTransformGetLabel($input);
oLabel && oLabel.click(function(){aLink.trigger('click');});
var aLink = $('');
$input.addClass('jqTransformHidden').wrap('<span class="jqTransformRadioWrapper"></span>').parent().prepend(aLink);
$input.change(function(){
inputSelf.checked && aLink.addClass('jqTransformChecked') || aLink.removeClass('jqTransformChecked');
return true;
});
// Click Handler
aLink.click(function(){
if($input.attr('disabled')){return false;}
$input.trigger('click').trigger('change');
// uncheck all others of same name input radio elements
$('input[name="'+$input.attr('name')+'"]',inputSelf.form).not($input).each(function(){
$(this).attr('type')=='radio' && $(this).trigger('change');
});
return false;
});
// set the default state
inputSelf.checked && aLink.addClass('jqTransformChecked');
});
};
/***************************
TextArea
***************************/
$.fn.jqTransTextarea = function(){
return this.each(function(){
var textarea = $(this);
if(textarea.hasClass('jqtransformdone')) {return;}
textarea.addClass('jqtransformdone');
oLabel = jqTransformGetLabel(textarea);
oLabel && oLabel.click(function(){textarea.focus();});
var strTable = '<table cellspacing="0" cellpadding="0" border="0" class="jqTransformTextarea">';
strTable +='<tr><td id="jqTransformTextarea-tl"></td><td id="jqTransformTextarea-tm"></td><td id="jqTransformTextarea-tr"></td></tr>';
strTable +='<tr><td id="jqTransformTextarea-ml"> </td><td id="jqTransformTextarea-mm"><div></div></td><td id="jqTransformTextarea-mr"> </td></tr>';
strTable +='<tr><td id="jqTransformTextarea-bl"></td><td id="jqTransformTextarea-bm"></td><td id="jqTransformTextarea-br"></td></tr>';
strTable +='</table>';
var oTable = $(strTable)
.insertAfter(textarea)
.hover(function(){
!oTable.hasClass('jqTransformTextarea-focus') && oTable.addClass('jqTransformTextarea-hover');
},function(){
oTable.removeClass('jqTransformTextarea-hover');
})
;
textarea
.focus(function(){oTable.removeClass('jqTransformTextarea-hover').addClass('jqTransformTextarea-focus');})
.blur(function(){oTable.removeClass('jqTransformTextarea-focus');})
.appendTo($('#jqTransformTextarea-mm div',oTable))
;
this.oTable = oTable;
if($.browser.safari){
$('#jqTransformTextarea-mm',oTable)
.addClass('jqTransformSafariTextarea')
.find('div')
.css('height',textarea.height())
.css('width',textarea.width())
;
}
});
};
/***************************
Select
***************************/
$.fn.jqTransSelect = function(){
return this.each(function(index){
var $select = $(this);
if($select.hasClass('jqTransformHidden')) {return;}
if($select.attr('multiple')) {return;}
var oLabel = jqTransformGetLabel($select);
/* First thing we do is Wrap it */
var $wrapper = $select
.addClass('jqTransformHidden')
.wrap('<div class="jqTransformSelectWrapper"></div>')
.parent()
.css({zIndex: 10-index})
;
/* Now add the html for the select */
$wrapper.prepend('<div><span></span></div><ul></ul>');
var $ul = $('ul', $wrapper).css('width',$select.width()).hide();
/* Now we add the options */
$('option', this).each(function(i){
var oLi = $('<li>'+ $(this).html() +'</li>');
$ul.append(oLi);
});
/* Add click handler to the a */
$ul.find('a').click(function(){
$('a.selected', $wrapper).removeClass('selected');
$(this).addClass('selected');
/* Fire the onchange event */
//if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); }
if ($select[0].selectedIndex != $(this).attr('index')) { $select[0].selectedIndex = $(this).attr('index'); $select.change(); }
//Redundent code
//$select[0].selectedIndex = $(this).attr('index');
$('span:eq(0)', $wrapper).html($(this).html());
$ul.hide();
return false;
});
/* Set the default */
$('a:eq('+ this.selectedIndex +')', $ul).click();
$('span:first', $wrapper).click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
oLabel && oLabel.click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
this.oLabel = oLabel;
/* Apply the click handler to the Open */
var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper)
.click(function(){
//Check if box is already open to still allow toggle, but close all other selects
if( $ul.css('display') == 'none' ) {jqTransformHideSelect();}
if($select.attr('disabled')){return false;}
$ul.slideToggle('fast', function(){
var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
$ul.animate({scrollTop: offSet});
});
return false;
})
;
// Set the new width
var iSelectWidth = $select.outerWidth();
var oSpan = $('span:first',$wrapper);
var newWidth = (iSelectWidth > oSpan.innerWidth())?iSelectWidth+oLinkOpen.outerWidth():$wrapper.width();
$wrapper.css('width',newWidth);
$ul.css('width',newWidth-2);
oSpan.css({width:iSelectWidth});
// Calculate the height if necessary, less elements that the default height
//show the ul to calculate the block, if ul is not displayed li height value is 0
$ul.css({display:'block',visibility:'hidden'});
var iSelectHeight = ($('li',$ul).length)*($('li:first',$ul).height());//+1 else bug ff
(iSelectHeight < $ul.height()) && $ul.css({height:iSelectHeight,'overflow':'hidden'});//hidden else bug with ff
$ul.css({display:'none',visibility:'visible'});
});
};
$.fn.jqTransform = function(options){
var opt = $.extend({},defaultOptions,options);
/* each form */
return this.each(function(){
var selfForm = $(this);
if(selfForm.hasClass('jqtransformdone')) {return;}
selfForm.addClass('jqtransformdone');
$('input:submit, input:reset, input[type="button"]', this).jqTransInputButton();
$('input:text, input:password', this).jqTransInputText();
$('input:checkbox', this).jqTransCheckBox();
$('input:radio', this).jqTransRadio();
$('textarea', this).jqTransTextarea();
if( $('select', this).jqTransSelect().length > 0 ){jqTransformAddDocumentListener();}
selfForm.bind('reset',function(){var action = function(){jqTransformReset(this);}; window.setTimeout(action, 10);});
//preloading dont needed anymore since normal, focus and hover image are the same one
/*if(opt.preloadImg && !jqTransformImgPreloaded){
jqTransformImgPreloaded = true;
var oInputText = $('input:text:first', selfForm);
if(oInputText.length > 0){
//pour ie on eleve les ""
var strWrapperImgUrl = oInputText.get(0).wrapper.css('background-image');
jqTransformPreloadHoverFocusImg(strWrapperImgUrl);
var strInnerImgUrl = $('div.jqTransformInputInner',$(oInputText.get(0).wrapper)).css('background-image');
jqTransformPreloadHoverFocusImg(strInnerImgUrl);
}
var oTextarea = $('textarea',selfForm);
if(oTextarea.length > 0){
var oTable = oTextarea.get(0).oTable;
$('td',oTable).each(function(){
var strImgBack = $(this).css('background-image');
jqTransformPreloadHoverFocusImg(strImgBack);
});
}
}*/
}); /* End Form each */
};/* End the Plugin */
})(jQuery);
You could also get the same here: http://pastebin.com/Q1pYMKZ2

Categories