Pseudocode:
My jQuery code is as following:
$(document).ready(function () {
var $window = $(window);
function checkWidth() {
//set main vars
var windowsize = $window.width();
var $sideBarContent = $('#sidebar .dummy-content');
var $placeHolder = $('#place-holder');
//perform the main check
if (windowsize >= 768 && $('#place-holder').length) {
$($sideBarContent).clone(true)
.appendTo($($placeHolder));
}
else {
$($placeHolder).hide();
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});
But the problem is that at the first page load everything is performed well, but at resize and back again, the script is not doing his job. Also on each resize all the content from the sidebar, is entered several times into the placeholder (instead of once).
I just do not know what I'm doing wrong.
A few problems:
placeHolder
div again!$()
around jQuery variablese.g.
$(document).ready(function () {
var $window = $(window);
function checkWidth() {
//set main vars
var windowsize = $window.width();
var $sideBarContent = $('#sidebar .dummy-content');
var $placeHolder = $('#place-holder');
//perform the main check
if (windowsize >= 768) {
if (!$placeHolder.children().length) {
$sideBarContent.clone(true)
.appendTo($placeHolder);
}
$placeHolder.show();
} else {
$placeHolder.hide();
}
}
// Bind event listener and do initial execute
$window.resize(checkWidth).trigger("resize");
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/jtfv4jjt/8/
Note: Your code can be simplified further as you only need to clone once at start and then just toggle visibility of that panel.
e.g.
$(document).ready(function () {
var $window = $(window);
var $sideBarContent = $('#sidebar .dummy-content');
var $placeHolder = $('#place-holder');
function checkWidth() {
$placeHolder.toggle($window.width() >= 768);
}
// Clone at start - then hide it
$sideBarContent.clone(true).appendTo($placeHolder);
// Bind event listener and do initial execute
$window.resize(checkWidth).trigger("resize");
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/jtfv4jjt/6/
Again this can be shortened:
$(function () {
var $window = $(window);
var $sideBarContent = $('#sidebar .dummy-content');
var $placeHolder = $('#place-holder');
// Clone content at start - then hide it
$sideBarContent.clone(true).appendTo($placeHolder);
// Bind event listener and do initial execute
$window.resize(function(){
$placeHolder.toggle($window.width() >= 768)
}).trigger("resize");
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/jtfv4jjt/7/
That's all for now :)
If you use Twitter bootstrap, you can simply decorate the panel with an appropriate class (something like visible-md
) and all this will happen for you :)