How to change id of div element when browser resize? - javascript

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>

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 remove and recreate element with jquery?

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.

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.

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.

Scroll event background change

I am trying to add a scroll event which will change the background of a div which also acts as the window background (it has 100% width and height). This is as far as I get. I am not so good at jquery. I have seen tutorials with click event listeners. but applying the same concept , like, returning scroll event as false, gets me nowhere. also I saw a tutorial on SO where the person suggest use of array. but I get pretty confused using arrays (mostly due to syntax).
I know about plugins like waypoints.js and skrollr.js which can be used but I need to change around 50-60 (for the illusion of a video being played when scrolled) ... but it wont be feasible.
here is the code im using:-
*
{
border: 2px solid black;
}
#frame
{
background: url('1.jpg') no-repeat;
height: 1000px;
width: 100%;
}
</style>
<script>
$(function(){
for ( i=0; i = $.scrolltop; i++)
{
$("#frame").attr('src', ''+i+'.jpg');
}
});
</script>
<body>
<div id="frame"></div>
</body>
Inside your for loop, you are setting the src attribute of #frame but it is a div not an img.
So, instead of this:
$("#frame").attr('src', ''+i+'.jpg');
Try this:
$("#frame").css('background-image', 'url(' + i + '.jpg)');
To bind a scroll event to a target element with jQuery:
$('#target').scroll(function() {
//do stuff here
});
To bind a scroll event to the window with jQuery:
$(window).scroll(function () {
//do stuff here
});
Here is the documentation for jQuery .scroll().
UPDATE:
If I understand right, here is a working demo on jsFiddle of what you want to achieve.
CSS:
html, body {
min-height: 1200px; /* for testing the scroll bar */
}
div#frame {
display: block;
position: fixed; /* Set this to fixed to lock that element on the position */
width: 300px;
height: 300px;
z-index: -1; /* Keep the bg frame at the bottom of other elements. */
}
Javascript:
$(document).ready(function() {
switchImage();
});
$(window).scroll(function () {
switchImage();
});
//using images from dummyimages.com for demonstration (300px by 300px)
var images = ["http://dummyimage.com/300x300/000000/fff",
"http://dummyimage.com/300x300/ffcc00/000",
"http://dummyimage.com/300x300/ff0000/000",
"http://dummyimage.com/300x300/ff00cc/000",
"http://dummyimage.com/300x300/ccff00/000"
];
//Gets a valid index from the image array using the scroll-y value as a factor.
function switchImage()
{
var sTop = $(window).scrollTop();
var index = sTop > 0 ? $(document).height() / sTop : 0;
index = Math.round(index) % images.length;
//console.log(index);
$("#frame").css('background-image', 'url(' + images[index] + ')');
}
HTML:
<div id="frame"></div>
Further Suggestions:
I suggest you change the background-image of the body, instead of the div. But, if you have to use a div for this; then you better add a resize event-istener to the window and set/update the height of that div with every resize. The reason is; height:100% does not work as expected in any browser.
I've done this before myself and if I were you I wouldn't use the image as a background, instead use a normal "img" tag prepend it to the top of your page use some css to ensure it stays in the back under all of the other elements. This way you could manipulate the size of the image to fit screen width better. I ran into a lot of issues trying to get the background to size correctly.
Html markup:
<body>
<img src="1.jpg" id="img" />
</body>
Script code:
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200) {
// function goes here
$('img').attr('src', ++count +'.jpg');
}
});
});
I'm not totally sure if this is what you're trying to do but basically, when the window is scrolled, you assign the value of the distance to the top of the page, then you can run an if statement to see if you are a certain point. After that just simply change run the function you would like to run.
If you want to supply a range you want the image to change from do something like this, so what will happen is this will allow you to run a function only between the specificied range between 200 and 400 which is the distance from the top of the page.
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200 && topPage < 400) {
// function goes here
$('#img').attr('src', ++count +'.jpg');
}
});
});

Categories

Resources