Reputation: 117
I'm having trouble with the onResize event. I have an if/else statement that checks if the window is resized < 768. The code works great but on every resize, it duplicates my prepend on every resize event trigger. Is there a way to make it happen only exceeding or below the 767 window size?
<div class="author-wrap">
<div class="the">Sample</div>
</div>
onResize:
onResize = function() {
var responsive_viewport = $(window).width();
if (responsive_viewport < 768) {
$('.the').prepend('<h3>Hi</h3>');
} else {
}
}
$(document).ready(onResize);
$(window).bind('resize', onResize);
Here's the code on jsfiddle to see it in action: http://jsfiddle.net/K7Ugc/1/
Upvotes: 0
Views: 173
Reputation: 1308
Check if the prepended element already exists. I have in mind this tricky way
onResize = function() {
var responsive_viewport = $(window).width();
var author_page = $('.main-content.author-archive');
var author_name = $('h3.cat-label strong').text();
var author_wrap = $('.author-wrap');
if (responsive_viewport < 768) {
if (!$('.the h3').text()){
$('.the').prepend('<h3>Hi</h3>');
}
} else {
}
}
$(document).ready(onResize);
$(window).bind('resize', onResize);
Upvotes: 1
Reputation: 531
Are you looking for it to only run once? You can unbind the event if that's what you're looking to do:
onResize = function() {
var responsive_viewport = $(window).width();
var author_page = $('.main-content.author-archive');
var author_name = $('h3.cat-label strong').text();
var author_wrap = $('.author-wrap');
if (responsive_viewport < 768) {
alert(responsive_viewport);
$('.the').prepend('<h3>Hi</h3>');
$(window).unbind();
} else {
}
}
Upvotes: 0