javascript - Remove element at specific screen width with jquery? -


i'm building responsive site mobile first approach need add html element when screen larger 641px , remove when less. problem i'm having when resize screen larger 641px code produces infinite numbers of said element , when reduce screen size there masses amounts of space when removed.

my code looks this:

<script>         $(function () {             $(window).resize(function () {                 if ($(window).width() > 641) {                      $('.project_nav').append('<li><a class="work_grid" href="#"><img src="images/noun_project_5193.svg"/> </a></li>');                 } else {                     $('.work_grid').remove();                 }             });         });     </script> 

and here's html want append:

<div class="project_nav">             <ul>                 <li><a class="up_arrow" href="#"><img src="images/noun_project_6978.svg"/> </a></li>                 <li><a class="prev_arrow" href="#"><img src="images/noun_project_6976.svg"/> </a></li>                 <li><a class="next_arrow" href="#"><img src="images/noun_project_6977.svg"/> </a></li>             </ul>         </div> 

any appreciated!

you need keep track of if element has been added or removed. easiest way without pounding dom store in variable:

    $(function () {         var isadded = false;         $(window).resize(function () {             if (!isadded && $(window).width() > 641) {                  isadded = true;                  $('.project_nav').append('<li class="work_grid_container"><a class="work_grid" href="#"><img src="images/noun_project_5193.svg"/> </a></li>');             } else if (isadded && $(window).width() <= 641) {                 isadded = false;                 $('.work_grid_container').remove();             }         });     }); 

this way add element if hasn't been added , remove if exists on page.

note: need have selector li instead of a! otherwise keep adding lis. need remove added.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -