0

Problem: I want to display only the result for one <li> element, not for all of them.

If you have any questions please do ask.

Javascript:

function func1(i){
  $('el[i] ~ span#showOrNo').css({'display':''}); //doesn't work
  //$('span#showOrNo').css({'display':''}); this works, but displays all elements
}

function func2(i){
  $('el[i] ~ span#showOrNo').css({'display':'none'});
  //$('span#showOrNo').css({'display':'none'});
}

var el = $('li');
for(var i = 0; i < el.length; i++){
  el[i].addEventListener('mouseover', function(){
    func1(i);
  }, false);
  el[i].addEventListener('mouseout', function(){
    func2(i);
  }, false);
}

Html:

{% for song in songs %}
  <li>
    <div>
      <span>{{ song.name }}-{{ song.artist }}</span>
      <div id="showOrNo", style='display:none'>
        {% if song.attr %}
        <span>{{ song.attr }}</span>
        {% else %}
        <span>{{ song.change }}</span>
        {% endif %}
      </div>
    </div>
  </li>
4
  • So... you want to show only the LI that gets clicked... is that it? Commented Feb 17, 2015 at 21:12
  • 1
    You know that you are using the same id for every li, don't you? Commented Feb 17, 2015 at 21:17
  • @Selcuk How? I am incrementing i. Sorry if it's a noob question. I just started with js. Commented Feb 18, 2015 at 6:14
  • @dylrei I want to show the div showOrNo for just that li that gets hovered on. Commented Feb 18, 2015 at 6:16

1 Answer 1

1

You have to use unique ids in your HTML but you don't need to bind your event to a specific id in this case. Try this:

HTML:

<li>
<div>
  <span>{{ song.name }}-{{ song.artist }}</span>
  <div class="showOrNo" style='display:none'>
    {% if song.attr %}
    <span>{{ song.attr }}</span>
    {% else %}
    <span>{{ song.change }}</span>
    {% endif %}
  </div>
</div>

And in your JS, use a class selector:

function func1() {
    $(this).find('div.showOrNo').css({'display':''});
}

function func2() {
    $(this).find('div.showOrNo').css({'display':'none'});
}

$('li').on('mouseover', func1);
$('li').on('mouseout', func2);

This will bind every li in your HTML document and when you mouseover/out, it will find the first div with a class containing showOrNo. You can see the result here: http://jsfiddle.net/7qx5ge9m/1/

Sign up to request clarification or add additional context in comments.

1 Comment

Works now. Thank you. Jquery for the win!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.