jQuery Question

How to change value of $() selector on fly to use it without reloading content?

I want to display hidden p[i] for each .cont[i] onclicked, and each event may appear only once.

html structure:

<div class="cont0">
<p></p>
</div>
<div class="cont1">
<p></p>
</div>
<div class="cont2">
<p></p>
</div>


for this purpose i thought would be better to use something like this:

$(document).ready(function() {
$("p").hide();
currentItem = 0;
currentCont = ".cont" + currentItem.toString();
mArrayList = ["a", "b", "c"];
currentArrayElement = mArrayList[currentItem];

$(currentCont).on("click", function(){
$(currentCont + " p").fadeIn(3000).html(currentArrayElement);
currentItem+=1;
});
});


but after 1st oncklick, it can't find .cont1 as expected (for me)..
only one thing i found here - to redefine variables outside the function, i tried this:

nextCurrentItem = function nextCurrentItem() {
currentItem += 1;
currentArrayElement = mArrayList[currentItem];
};

changeCont = function changeCont() {
currentCont = ".cont" + currentItem.toString();
};

$(currentCont).on("click", function(){
$(currentCont + " p").delay(300).fadeIn(3000).html(currentArrayElement);
nextCurrentItem();
changeCont();
});
});


but function's behavior is still the same. Also tried to add/remove class "selected" to next div - behavior is the same as previous.

Could you give me advice how to solve this problem (with 1 click on each element to invoke my event)?

Thank you!

Answer Source

Your code only attaches the event to the first DIV.

Give the DIVs an ID and the same class to do this

var mArrayList = ["a", "b", "c"];
$(function() {
  $(".fadeP").on("click", function() {
    $("p",this).fadeIn(3000).html(mArrayList[this.id.replace("cont","")]);
  });
});
.fadeP>p { display:none }
#cont0 { border:1px solid red; height:50px }
#cont1 { border:1px solid yellow; height:50px }
#cont2 { border:1px solid green; height:50px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fadeP" id="cont0">
  <p>Paragraph 0</p>
</div>
<div class="fadeP" id="cont1">
  <p>Paragraph 1</p>
</div>
<div class="fadeP" id="cont2">
  <p>Paragraph 2</p>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download