How to add and remove an element to the page when decreasing/ increasing screen sizes?

Need some to rebuild the markup for the page on small resolution means jquery. Namely, when reaching a certain size of screen to add a div element
$(window).resize(function() {
 if ( $(window).width() < 1024 ) {
 $('#col_slider').append('<div class="col-xs-6" id="col_mobile-slider"></div>');
}
 return false;
});

My code looks on the page the element with id col_slider and adds
<div class="col-xs-6" id="col_mobile-slider"></div>
. But he does it all the time when it reaches the width of the screen <1024 . How to make a function to run 1 and not run?
March 12th 20 at 08:03
2 answers
March 12th 20 at 08:05
Use media queries
March 12th 20 at 08:07
It is better to do using media queries, but if you really need using JQuery, here's a working example:

$(window).resize(function() {
 // check the width and whether there is a div #col_mobile-slider, thereby the body of the condition executed once
 if ($(window).width() < 1024 && $("#col_mobile-slider").length == 0) {
 $('#col_slider').append('<div class="col-xs-6" id="col_mobile-slider">Text!</div>');
}
 // Rolled back changes when you increase the width of the window (if needed)
 else if($(window).width() > 1024 && $("#col_mobile-slider").length == 1) {
$("#col_mobile-slider").remove();
}
 return false;
 });

Find more questions by tags jQuery