How to remove and recreate element with jquery? - javascript

I have elements and I want to remove this element on responsive but I want to recreate again on desktop
I mean I want to remove this element in if and I want to create again in else
my project is something like that
$(window).resize(function(){
var width = $(window).width();
if(width <=768){
$('.element').remove();
}else{
//create again
}
}).resize();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element">
<p>something here..</p>
</div>
footnote: please I don't want to hide it because it div is showing when I scroll then if I hide it after scroll on mobile then it will be shown again..

If you really want to remove the element, don't actually use remove() when you want to reinsert it again. Use detach() (https://api.jquery.com/detach/)
The following is an example from Re-attaching jQuery detach();
var el = $('.element');
if(width <=768){
el.detach();
}else{
$(body).append(el);
}
Detaching ensures that the element keeps jQuery data associated with it for later use.

Why dont you try hide and show, because if you remove it you will need some hidden element to clone it or add it back. I would suggest you using hide/show
$(window).resize(function(){
var width = $(window).width();
if(width <=768){
$('.element').hide();
}else{
$('.element').show();
}
}).resize();
or using css media query
#media(screen and max-width: 768px) {
.element {
display: none;
}
}
or if you want to use remove then make a global variable and assing .element to it.
var obj = $(".element");
$(window).resize(function(){
var width = $(window).width();
if(width <=768){
$('.element').remove();
}else{
$('body').append(obj);
}
}).resize();

Why would you want to delete and restore it for a responsive-like design? You could be using CSS Media-Queries instead, which is much more resource-friendly and overall the better approach:
#media(screen and max-width: 768px) {
.element {
display: none;
}
}
If you would have to use JS, you should use .hide() and .show(), which essentially does the same thing except via JQuery:
$(window).resize(function() {
var width = $(window).width();
if(width <= 768) {
$('.element').hide();
}
else {
$('.element').show();
}
}).resize();
If I'm not getting your point and you actually have to do it the JS way via deleting and restoring, please let me know in a comment and I will try to help.

Related

Using JavaScript to delete div in screen size below a certain pixel

I'm a newbie in coding. I knew this can be done by css, but want to do it by using JavaScript.
I have a div tag and would like to not show it under 630px screen size. I searched this site and find this JavaScript code in another question and I liked it:
if( window.innerWidth > 630 ) {
//Your Code
}
But as I'm newbie I'm not familiar on how to insert it in my PHP code and where to insert div so it only works for screen above 630px.
Here is a way to hide a div when the width of the screen is smaller then 700px
function myFunction(x) {
if (x.matches) { // If media query matches
document.getElementById("divIWantedToHide").style.visibility = "hidden";
} else {
document.getElementById("divIWantedToHide").style.visibility = "visible";
}
}
var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction)
<div id="divIWantedToHide">
tset
</div>
Fiddle
Personally I would recommend you to use CSS for this to be more precise media querys.
#media only screen and (max-width: 700px) {
#divIWantedToHide {
display: none;
}
}
<div id="divIWantedToHide">
tset
</div>
Fiddle
This is more of an event issue:
At the basic level, this is how you could toggle by resize event:
var el = document.getElementById("yes"); //get the element node
//target resize event
window.onresize = function(){
//this will check everytime a resize happens
if(window.innerWidth > 630)
{
//if width is still bigger than 630, keep the element visible
el.style.display = "block";
//exit the funtion
return;
}
//At this point, the width is less than or equals to 630, so hide the element
el.style.display = "none";
}
<div id="yes">
Yey! I am visible
</div>

How to change id of div element when browser resize?

I have this code
<div id="123"></div>
i want to change the id to 234 when the browser resized
<div id="234"></div>
I have use media query , but i think it is not possible
#media screen and (max-width: 479px) {
#123 {
}
}
You can do this easily with javascript or jQuery.
Here a example written in JS.
window.onresize = function(){
var div = document.getElementById("aaa");
if(div){
div.setAttribute("id", "bbb");
}
}
#aaa {
font-size: 10px;
}
#bbb {
font-size: 10em;
}
<div id="aaa">Resize</div>
Im not sure what you are trying to do but this can be solved with window.onresize
You generally shouldn't be changing your element IDs around but if you want to you will need some logic in the onresize function to deduce which ID your element will have when you resize your window.
You're right! It's not possible to do with CSS, but it can be possible to do with JavaScript &/or jQuery. Try this using jQuery:
$(window).on('resize',function() {
$('#123').attr('id','234');
});
The problem with the code above, is that it's a 1x only change. You could never re-target that id after the first resize. So after the browser detects that it has been resized by 2-3 pixels, then the JS will break.
The real question is, why would you want to change an id on resize? It would be better to change an HTML 5 data-* attribute, like: data-id. This allows you to be able to change it repeatedly, using the #myUniqueId attribute. Then your code should continue to run continuously, for as long as the window is being resized.
Here is a jsfiddle for this code:
HTML:
<div id="myUniqueId" data-id="123"></div>
<div id="output"></div>
jQuery:
$(window).resize(function() {
var id = $('#myUniqueId').attr('data-id');
id++;
$('#myUniqueId').attr('data-id',id);
// Double check: what is my id?
var myId = $('#myUniqueId').attr('data-id');
$('#output').html(myId);
});
I use similiar code so you can use different css for mobile or desktop... However it completely irritates me.
This way you use the same id or class. But depending on screen size it will do something different.
#media not all and (min-width:999px){
/* Big Screen */
body {background-color:green; }
#id { background-color:red}
}
#media all and (min-width:1000px)
{
/* Smaller Screen */
body {background-color:blue; }
#id { background-color:grey}
}
Notice how when you manually re size the screen with your mouse the color changes....to the smaller css automatically.
No jQuery answer
window.onresize = function(event) {
if(document.getElementById('123') != null)
document.getElementById('123').id = '234';
};
Just be careful id 234 is not assigned to another element, however you should not be changing your id for changing styles as it should be done by adding and removing css classes.
I hope this one work for you.
//detect window resize
$(window).resize(function() {
//test if window width is below 479
$(window).width() < 479 ? small() : big();
//small function is called when window size is smaller than 479
function small(){
//edited from $( "#id_changer" ).append( "<div id='123'>123</div>" );
document.getElementByID('id_changer').innerHTML = "<div id='123'>123</div>";
}
//big function is called when window size is bigger than 479
function big(){
//edited from $( "#id_changer" ).append( "<div id='234'>234</div>" );
document.getElementByID('id_changer').innerHTML = "<div id='234'>234</div>";
}
});
<body>
<div id="id_changer"></div>
</body>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script src="test.js"></script>

How to rearrange several divs on window resize - jQuery or CSS

I would like to ask for some advice or idea how to change the position of several divs when the window is resized (for example on a mobile device).
The problem is that I cannot create one div for a desktop user, copy the same div for a mobile user and then do display:none for one of those depending on the window size because the divs have to have unique id.
So I need to do it either with CSS or jQuery. Any ideas will be appreciated. This is what I need:
Here is a JSFiddle
Thank you!
you can use media queries for that
#media (max-width:768px){
.b, .a {
display: block;
float: none;
height: auto;
}
}
JS
var flag =true;
$( window ).resize(function() {
if($(this).width() <= 768){
if(flag){
var b1 = $('.b1').clone();
var a2= $('.a2').clone();
$('.a').find('.a2').remove();
$('.b').find('.b1').remove();
$('.a').append(b1);
$('.b').prepend(a2)
flag= false;
}
}else{
if(!flag){
var b1 = $('.b1').clone();
var a2= $('.a2').clone();
$('.a').find('.b1').remove();
$('.b').find('.a2').remove();
$('.a').append(a2);
$('.b').prepend(b1)
flag= true;
}
}
});
I updated your fiddle https://jsfiddle.net/36fh7hn3/5/
Use flexbox with the 'order' property and media queries.
Or this could possibly be achieved using the 'float' property and media queries depending upon your use case.

combine conditions if browser window is X height and element is scrolled to X point within

I've started with the below which works perfect, but I only need this to run and execute when my nav element .mainNav is scrolled to within a certain point within browser height.
#media screen and (max-height: 660px) {
.mainNav {
margin-top:-130px !important;
}
}
So detecting vertical browser height WITH scroll position within then chain .css with jQuery to. (margin-top:-100px)
Basically how to combine above parameter with below parameter. Below detects scroll position...
var $document = $(document),
$element = $('#some-element'),
className = 'hasScrolled';
$document.scroll(function() {
if ($document.scrollTop() >= 50) {
// user scrolled 50 pixels or more;
// do stuff
$element.addClass(className);
} else {
$element.removeClass(className);
}
});
You could do this by using the clientBoundingRect of the element. For example (untested, just theory);
var mainNav = document.getElementsByClassName('.mainNav')[0];
window.onscroll(function(e){
if(mainNav.clientBoundingRect().top <= 100 && window.height <= 660){
mainNav.style.marginTop = "-130px";
// or you could add a class here, as per the suggestion above, such as
// mainNav.setAttribute('class', 'mainNav locked');
}else{
mainNav.style.marginTop = "0";
// and remove it here
// mainNav.setAttribute('class', 'mainNav');
}
})
There is no visbility pseudo-selector in CSS, so you're looking at implementing this using JS handing of the visibilitychange event on your element, and then toggling the right (sequence of) class(es) through the element.classList interface, probably with transition rules in the CSS itself for the properties you want to be dynamic.

How to append html element one time when specific screen resolution range occurs?

My html:
<div id="log">
</div>
My jQuery:
$(function() {
var win = $(window);
resizeHandler();
win.resize(resizeHandler);
function resizeHandler() {
if (win.width() <= 700) {
$("#log").append("<div>" + "success" + "</div>");
}
}
});
I want that when a specific screen resolution range occurs, the <div>success</div> element would be displayed one time in the "log" div element. For example: from 1 px to 700 px screen resolution the success must be displayed in the "log" div element one time, and when the screen resolution is out of the 1 px to 700 px range the <div>success</div> must be removed from the "log" div element. How should the code look like?
$(function() {
var win = $(window);
resizeHandler();
win.resize(resizeHandler);
function resizeHandler() {
if (win.width() >= 700) {
if ($('#log').children().length == 0)
$("#log").append("<div class='suc'>" + "success" + "</div>");
} else {
$('.suc').remove();
}
}
});
If you really want to append just one element. But, i would use media queries too, and hide/show desired element...
Based on information provided in the comments, you want a simple media query. No JS required. If that's what you really needed to do then #nevermind's answer was perfect.
Just change your code like this.
HTML:
<div id="log">
<div id="success">Success</div>
</div>
CSS:
#success {
display: none;
}
#media only screen and (max-width: 700px) {
#success {
display: block;
}
}
You could create a boolean variable and set it to true when appending
+ create an else statement in your resizeHandler to cope with the other screensizes.
But in a real world example i would have solved this issue by using CSS mediaqueries.

Categories

Resources