On text change of anchor tag show/hide a div with JavaScript

Viewed 192

I want div lds-roller to only show while the text an ID searchFor anchor tag is equal to _. The change in text should happen with an HTTP response.

<div class="lds-roller"><div></div><div></div><div>
</div><div></div><div></div><div></div>
<div></div><div></div></div>
                <p>
                      <span class="r"> 
                               <span class="andom">
                                  <a href="{% pageurl post %}#disqus_thread" id="searchFor"> _
                                            </a>
                                </span>
                      </span>
                  </p>

Css for lds-roller is as follows.

.lds-roller {
  display: inline-block;
  position: relative;
  width: 64px;
  height: 64px;

I have tried numerous ways but they seem to always either keep showing the div, not displaying the div or making the div disappear before the text has even changed.

JS function has usually gone along the lines of this

$(function () {
   if ($("#searchFor").text() === "_")
   {
       $('.lds-roller').show();
   }
   else{
       $('.lds-roller').hide();
   }

})();
2 Answers

You will need to bind the function to an event. For example in jQuery you can use something like this:

    $("body").on('DOMSubtreeModified', "#searchFor", function() {
         if ($("#searchFor").text() === "_") {
           $('.lds-roller').show();
         }
         else {
          $('.lds-roller').hide();
         }

    });

At the moment, your code is running once on load time and that is why it only shows the div.

You need to change in your js code. it should be like this :

$(function () {
   if ($("#searchFor").text() === "_")
   {
       $('.lds-roller').show();
   }
   else{
       $('.lds-roller').hide();
   }
});

and its works fine for me

Related