开发者

How can I factor this jQuery and not repeat myself?

开发者 https://www.devze.com 2023-01-25 11:56 出处:网络
I have three layers, two of which are hidden using CSS. I would like to make those layers visible/invisible开发者_开发问答 depending on which input the user focuses on:

I have three layers, two of which are hidden using CSS. I would like to make those layers visible/invisible开发者_开发问答 depending on which input the user focuses on:

The three I'm changing are layers are: #titleBox, #phoneBox, #addressBox, the inputs are #title, #phone, #address. The #titleBox is the only one visible on page load.

$("#title").focus(function () {
    $("#phoneBox,#addressBox").hide();
    $("#titleBox").fadeIn("slow");
});
$("#phone").click(function () {
    $("#addressBox,#titleBox").hide();
    $("#phoneBox").fadeIn("slow");
});
$("#address").click(function () {
    $("#titleBox,#phoneBox").hide();
    $("#addressBox").fadeIn("slow");
});


The first piece of jQuery (below) doesn't work, but I'm leaving it as evidence of my own idiocy, the stuff after the <hr /> does, however, work.

$("#containerElement input").focus(function () {
    $(div:not'(#'+ this.id '+Box)').hide();
    $('#' + this.id + 'Box').fadeIn('slow');
});


Edited:

Because, basically, the above didn't really work that well. The following, however, does:

html:

<div id="containerElement">
    <input type="text" id="address" />
    <input type="text" id="phone" />
    <input type="text" id="title" />
</div>

<div id="otherContainer">
    <div id="addressBox">addressBox</div>
    <div id="phoneBox">phoneBox</div>
    <div id="titleBox">titleBox</div>
</div>

jQuery:

$(document).ready(
    function(){
        $("#containerElement input").focus(function () {
            var showThis = this.id + 'Box';
            $(this).val(showThis);
            $('#otherContainer div:not(#' + showThis + ')').hide();
            $('#'+showThis).fadeIn('slow');
        });
    });

JS Fiddle demo.


This will cache the "Box" elements, then pull the ID from the ones with the event, and .hide() or .fadeIn() the proper one using jQuery's .not() and .filter() methods.

Since you're using 2 different events, I've created a function that can be reused for both.

Example: http://jsfiddle.net/besMe/

// cache the boxes
var $boxes = $('#titleBox,#phoneBox,#addressBox');

// create reusable function that can be applied as click and focus handlers
function boxSwitch( e ) {
    $boxes.not('#' + this.id + 'Box').hide();
    $boxes.filter('#' + this.id + 'Box').fadeIn('slow');
}

// apply the handler
$("#title").focus(boxSwitch);
$("#phone,#address").click(boxSwitch);

EDIT: Corrected mistake. Should have had .filter() instead of .is().


$('.input-class-selector').bind('focus', function (event) {

    var el = $('#' + $(this).attr('id'));

    if (!$(el).is(':hidden')) {

       $('.layers-class-selector').hide();
       $(el).fadeIn('slow');

    }

});
0

精彩评论

暂无评论...
验证码 换一张
取 消