Nrc
Nrc

Reputation: 9787

How do I call a dynamic selector in jQuery?

I have a div that I change the id. I have checked that the new id is there. Then I call the new id to do something else and nothing happens.

How can I make the div do something only when it has a specific css? In the example, how can I fadeOut the div only when it is grey?

$("#red").click(function() {
  $('#red').attr('id', 'grey');
});

$("#grey").click(function() {
  $('#grey').attr('id', 'red');
  $('#grey').fadeOut(800);
});
#red{
	position: absolute;
	top:10px; left:10px;
	width:100px; height:100px;
	background-color:red;
	cursor:pointer;	
}
	
#grey{
	position: absolute;
	top:10px; left:150px; 
	width:100px; height:100px;
	background-color:grey;
	cursor:pointer;	
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="red"></div>

Upvotes: 1

Views: 59

Answers (2)

mituw16
mituw16

Reputation: 5250

Listeners are registered at page time. You're dynamically changing the content, attribute in this case, of the page. So instead of listening on the element it self, try listening on the document.

$(document).on("click", "#red", function() {
  $('#red').attr('id', 'grey');
});

$(document).on("click", "#grey", function() {
  var $ele = $(this);
  $ele.fadeOut(800, function() { $ele.attr('id', 'red').css("display", "block") });
});
#red{
  position: absolute;
  top:10px; left:10px;
  width:100px; height:100px;
  background-color:red;
  cursor:pointer;	
}
	
#grey{
  position: absolute;
  top:10px; left:150px; 
  width:100px; height:100px;
  background-color:grey;
  cursor:pointer;	
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="red"></div>

Upvotes: 1

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Since id changed dynamically, listeners stopped working as they can't access dynamically changed elements/attributes

So use jQuery .on()

Code need to be:-

$(document).on('click',"#red",function() {
    $(this).attr('id', 'grey');
});

$(document).on('click',"#grey",function() {
    $(this).attr('id', 'red');
});

Working snippet:-

$(document).on('click',"#red",function() {
  //$(this).attr('id', 'grey');
  //better to do same kind of effects
  $(this).fadeOut(800, function() { $(this).attr('id', 'grey').show(); });
});

$(document).on('click',"#grey",function() {
  $(this).fadeOut(800, function() { $(this).attr('id', 'red').show(); });
});
#red{
  position: absolute;
  top:10px; left:10px;
  width:100px; height:100px;
  background-color:red;
  cursor:pointer;	
}
	
#grey{
  position: absolute;
  top:10px; left:150px; 
  width:100px; height:100px;
  background-color:grey;
  cursor:pointer;	
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="red"></div>

Upvotes: 1

Related Questions