Hussein
Hussein

Reputation: 42818

pass clicked element as a variable to another function jquery

The code below assumes that the element we are clicking on is a div. What if the element clicked is unknown and we want to get the element type and id then pass it to the select change() function to change it's color. What is the best way to accomplish this.

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/themes/base/jquery-ui.css" type="text/css" media="all" /> 
  <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js" type="text/javascript"></script> 

<style>
    .aaa { width:100px; height:100px;background-color:#ccc;margin-bottom:5px;}
    p{widht:500px; height:500px; margin:0px; padding:0px;border:2px solid red;color:#000;}
</style>

<select id="item_select" name="item">
    <option value="1">red</option>
    <option value="2">blue</option>
    <option value="3">green</option>
</select>

<button>Click to create divs</button>
<p id="ptest"></p>

<script type="text/javascript">
var dividcount = 1;

$("button").click(function() {
    var myDiv = $('<div id=lar' + dividcount + ' class=aaa></div>');
    $(myDiv).appendTo('#ptest');

    dividcount++;
});

$('div').live('click', function() {

    $('div').removeClass('selected');
    $('div').html('');

    $(this).addClass('selected');
    $(this).html('div #' + this.id);
});

$('select').change(function() {
    $('div').each(function() {
        if ($(this).hasClass('selected')) {
            var str = $("select option:selected").text();
            $(this).css("background-color", str);
        }
    });
});
</script>

Upvotes: 1

Views: 2773

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388446

The event is binded to div elements so it will not get fired if you click on any other element. But I may prefer to use the delegate function.

var $ptest = $('#ptest');
$($ptest).delegate("div", 'click', function() {

    $('div', $ptest).removeClass('selected');
    $('div', $ptest).html('');

    $(this).addClass('selected');
    $(this).html('div #' + this.id);
});

This limit the click events to the divs created inside the #ptest element. and the $('div', $ptest).html(''); makes sure that the divs outside #ptest is not affected by the emptying operation.

You can see a working sample in this fiddle.

Upvotes: 2

Related Questions