Reputation: 73
Have been trying to get $("#id1").add();
and $("#id2").remove();
to work inside the following function taken from this post. I am getting the $("#id2").remove();
to work from the console and I would like to get them both to work from inside this function as well.
(function($) {
var $window = $(window),
function resize() {
if ($window.width() < 801) {
$("#id1").add();
$("#id2").remove();
}
else {
$("#id2").add();
$("#id1").remove();
}
}
$window
.resize(resize)
.trigger('resize');
})(jQuery);
Alternately, is could get it to work using .addClass/.removeClass, but then it has to target all sub classes as well..
Upvotes: 0
Views: 1822
Reputation: 19592
Media queries can be used to toggle the elements' visibility:
CSS
/* show id1, hide id2, when screen resolution is 800px or less */
@media screen and (max-width: 800px) {
#id1 {
display:block; /*or inline, or whatever */
}
#id2 {
display:none;
}
}
/* show id2, hide id1, when screen resolution is greater than 800px */
@media screen and (min-width: 801px) {
#id1 {
display:none;
}
#id2 {
display:block; /*or inline, or whatever */
}
}
But if they need to actually be added and removed from the DOM, then how about this
(function($) {
var $id1=$('#id1');
var $id1Parent=$id1.parent();
var $id2==$('#id2');
var $id2Parent=$id2.parent();
var $window = $(window),
function resize() {
$('#id1,#id2').remove();
if ($window.width() < 801) {
$id1Parent.append($id1);
}
else {
$id2Parent.append($id2);
}
}
$window
.resize(resize)
.trigger('resize');
})(jQuery);
Upvotes: 1
Reputation: 379
display none is the way to go for these kind of situations.
The other way is to use JQuery but it will be quite messy if your code gets longer. Or you might want to use AJAX for loading the div part if the div codes are really long.
function resize() {
if ($window.width() < 801) {
$("<div id='1'></div>").appendTo('.container'); //add it to your container
$("#id2").remove();
}
else ......
}
Upvotes: 0