Moving elements in DOM on resize using Javascript - javascript

First, please note that I'm using Elementor Pro for this project, then I can't use css easily because the html structure is complex. That's why I'm trying to do this with Javascript.
I'd like to move my image above my h1 title for tablets and mobile, and that it stays above the description on larger screens.
Here is my code (pure javascript, no jquery)
let title = document.getElementById("product-title");
let image = document.getElementById("product-image");
let resizeProductPage = function () {
if(typeof(title) != 'undefined' && title != null){
let width = window.innerWidth;
if (width<1025)
title.parentNode.insertBefore(image, title);
else
image.parentNode.insertBefore(title, image);
}
};
resizeProductPage();
window.addEventListener("resize", resizeProductPage);
but it doesn't work, and I find the code rather complex. would you have an idea?

Your code seems to be fine, but here is what you should do.
Under edit with elementor, at the component editor you
should be able to specify the ID for the title element to: product-title & the image element to: product-image
Your conditional checking if the title element exists should be adapted to just if (title) as it will return false if that element does not exist.
Other than that your code should be working fine, I made a working solution as a snippet.
let title = document.getElementById("product-title");
let image = document.getElementById("product-image");
let resizeProductPage = function() {
if (title) {
if (window.innerWidth < 1025)
title.parentNode.insertBefore(image, title);
else
image.parentNode.insertBefore(title, image);
}
};
resizeProductPage();
window.addEventListener("resize", resizeProductPage);
#product-image {
background: black;
text-align: center;
height: 200px;
width: 400px;
}
#product-image p {
color: #fff;
}
<h1 id="product-title">Product Title</h1>
<div id="product-image">
<p>Image Here</p>
</div>

Related

CSS attribute not always being grabbed by javascript correctly

I am trying to resize the side bars whenever the image changes.
I have my javascript trying grab the height of the image after it changes
var imgHeight = $('#mainImg').height();
var currImg = 0;
var imagesSet = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg"];
var imageLoc = "images/zalman/"
$('#bttnRight').click(function(){
nextImg();
imgHeight = $('#mainImg').height();
resizeBttn();
});
function nextImg(){
currImg++;
if(currImg>=imagesSet.length){
currImg=0;
}
$('#mainImg').attr("src",imageLoc + imagesSet[currImg]);
}
function resizeBttn() {
$(document).ready(function() {
$('#bttnLeft').css("height",imgHeight);
$('#bttnLeft').css("bottom",imgHeight/2-5);
});
$(document).ready(function() {
$('#bttnRight').css("height",imgHeight);
$('#bttnRight').css("bottom",imgHeight/2-5);
});
}
for some reason, it doesn't always grab the height at the correct time and the side bars will stay at the previous height.
Below I have a JSFiddle that should be working the way my setup is.
Please excuse any inconsistencies and inefficiencies, I am learning.
Just seems weird that it would sometimes grab the height and sometimes not.
I will also be attaching an image of what I see sometimes from the JSfiddle.
I will also attach an image of what I see on my site I am actually writing.
https://jsfiddle.net/6bewkuo5/6/
The issue is because your JavaScript accessing the height of the image before the image as actually been re-rendered in the DOM. Adding a slight delay after assigning the new image source may help things, but...
You actually don't need to use JavaScript to set the height of the buttons
You can achieve what you're after by placing the buttons and image inside of a container with css attribute display: flex.
Like this:
.container {
display: flex;
justify-content: center;
}
<div class="container">
<button class="prev"><</button>
<img src="https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif">
<button class="next">></button>
</div>
Elements within a flex container will automatically fill the height, this includes buttons. Because the images will automatically adjust the height of the container, the buttons will also automatically adjust their height to match.
Run the example below
const images = [
"https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif",
"https://images.sftcdn.net/images/t_app-logo-xl,f_auto/p/ce2ece60-9b32-11e6-95ab-00163ed833e7/1578981868/the-test-fun-for-friends-logo.png",
"https://hiveconnect.co.za/wp-content/uploads/2018/05/800x600.png",
"https://upload.wikimedia.org/wikipedia/commons/b/b5/800x600_Wallpaper_Blue_Sky.png"
]
const imageEl = document.querySelector('img')
let imageIndex = 0
document.querySelector('.prev').addEventListener('click', e => {
if (--imageIndex < 0) { imageIndex = images.length - 1 }
imageEl.src = images[imageIndex]
})
document.querySelector('.next').addEventListener('click', e => {
if (++imageIndex > images.length - 1) { imageIndex = 0 }
imageEl.src = images[imageIndex]
})
body {
background-color: #206a5d;
color: #ffffff;
text-align: center;
}
.container {
display: flex;
justify-content: center;
}
img {
max-width: 50%;
}
<h1>Zalman Build</h1>
<div class="container">
<button class="prev"><</button>
<img src="https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif">
<button class="next">></button>
</div>
The reason is because the resizeBttn code is firing before the image has actually finished downloading and loading into the DOM. I made these changes in your fiddle:
var imgHeight = $('#mainImg').height();
var currImg = 0;
var imagesSet = ["https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif","https://images.sftcdn.net/images/t_app-logo-xl,f_auto/p/ce2ece60-9b32-11e6-95ab-00163ed833e7/1578981868/the-test-fun-for-friends-logo.png", "https://hiveconnect.co.za/wp-content/uploads/2018/05/800x600.png", "https://upload.wikimedia.org/wikipedia/commons/b/b5/800x600_Wallpaper_Blue_Sky.png"];
var imageLoc = "images/zalman/"
$(document).ready(function() {
resizeBttn();
});
$( window ).resize(function() {
/* imgHeight = $('#mainImg').height() */; // commented out; we do this in resizeBttn now
resizeBttn();
});
$('#bttnLeft').click(function(){
prevImg();
/* imgHeight = $('#mainImg').height() */; // commented out; we do this in resizeBttn now
/* resizeBttn() */; // we do this as an `onload` to the image now
});
$('#bttnRight').click(function(){
nextImg();
/* imgHeight = $('#mainImg').height() */; // commented out; we do this in resizeBttn now
/* resizeBttn() */; // we do this as an `onload` to the image now
});
function nextImg(){
currImg++;
if(currImg>=imagesSet.length){
currImg=0;
}
$('#mainImg').attr("src",imagesSet[currImg]);
}
function prevImg(){
currImg--;
if(currImg<0){
currImg=imagesSet.length-1;
}
$('#mainImg').attr("src",imagesSet[currImg]);
}
function resizeBttn() {
imgHeight = $('#mainImg').height()
// removed superfluous doc.ready
$('#bttnLeft').css("height",imgHeight);
$('#bttnLeft').css("bottom",imgHeight/2-5);
$('#bttnRight').css("height",imgHeight);
$('#bttnRight').css("bottom",imgHeight/2-5);
}
And then rewrote your <img /> tag to call resizeBttn on onload:
<img id="mainImg" src="https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif" onload="resizeBttn()"/>
You can see this in action in this fiddle.
Also, a few additional notes on your code, at a glance:
You have some invalid HTML; you're going to want to run that through an HTML validator and fix it, because sometimes it is fine, but sometimes it can lead to all sorts of strange behavior.
You're playing fast and l0ose with global variables in your JS that get set in different functions; it might work OK while the script is small, but as things scale it can quickly become difficult to maintain
You should really avoid abusing the onclick to get link-like behavior from <li> elements; it can impact SEO as well as accessibility. I'd recommend simply using an anchor element inside or outside the <li>
I'd recommend taking a close look at this answer by user camaulay; he makes an excellent point that this may not require JS at all- if a more elegant solution exists w/ CSS it is probably going to be more performant and maintainable.

editing image in javascript

I'm just playing with javascript and HTML but I can't solve one error.
I've created a button and added eventLister on it then I created a simple function which should set up the background image, but instead it's undefined
document.getElementById("failure").addEventListener("click" ,dang);
function dang(){
let info = prompt("Enter link to new IMG");
document.querySelector(".upperDivImage").style.backgroundImage = `url(${info})`;
console.log("gut")
}
This actually works. Here is a working example (of your code).
Notice that if you use a div you need to give it width and height for it to display
document.getElementById("failure").addEventListener("click", dang);
function dang() {
let info = prompt("Enter link to new IMG");
document.querySelector(".upperDivImage").style.backgroundImage = `url(${info})`;
console.log("gut")
}
.upperDivImage {
width: 200px;
height: 200px;
background-size: contain;
}
<div id="failure">click me</div>
<div class="upperDivImage" />

How do I scroll to an element which is present inside an overflow div which itself is inside an an overflow container? [duplicate]

I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.
I am wrapping everything in this div:
#scroll {
height:400px;
overflow:scroll;
}
Is there a way to keep it scrolled to the bottom by default using JS?
Is there a way to keep it scrolled to the bottom after an ajax request?
Here's what I use on my site:
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
This is much easier if you're using jQuery scrollTop:
$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
Try the code below:
const scrollToBottom = (id) => {
const element = document.getElementById(id);
element.scrollTop = element.scrollHeight;
}
You can also use Jquery to make the scroll smooth:
const scrollSmoothlyToBottom = (id) => {
const element = $(`#${id}`);
element.animate({
scrollTop: element.prop("scrollHeight")
}, 500);
}
Here is the demo
Here's how it works:
Ref: scrollTop, scrollHeight, clientHeight
using jQuery animate:
$('#DebugContainer').stop().animate({
scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);
Newer method that works on all current browsers:
this.scrollIntoView(false);
var mydiv = $("#scroll");
mydiv.scrollTop(mydiv.prop("scrollHeight"));
Works from jQuery 1.6
https://api.jquery.com/scrollTop/
http://api.jquery.com/prop/
alternative solution
function scrollToBottom(element) {
element.scroll({ top: element.scrollHeight, behavior: 'smooth' });
}
smooth scroll with Javascript:
document.getElementById('messages').scrollIntoView({ behavior: 'smooth', block: 'end' });
If you don't want to rely on scrollHeight, the following code helps:
$('#scroll').scrollTop(1000000);
Java Script:
document.getElementById('messages').scrollIntoView(false);
Scrolls to the last line of the content present.
My Scenario: I had an list of string, in which I had to append a string given by a user and scroll to the end of the list automatically. I had fixed height of the display of the list, after which it should overflow.
I tried #Jeremy Ruten's answer, it worked, but it was scrolling to the (n-1)th element. If anybody is facing this type of issue, you can use setTimeOut() method workaround. You need to modify the code to below:
setTimeout(() => {
var objDiv = document.getElementById('div_id');
objDiv.scrollTop = objDiv.scrollHeight
}, 0)
Here is the StcakBlitz link I have created which shows the problem and its solution : https://stackblitz.com/edit/angular-ivy-x9esw8
If your project targets modern browsers, you can now use CSS Scroll Snap to control the scrolling behavior, such as keeping any dynamically generated element at the bottom.
.wrapper > div {
background-color: white;
border-radius: 5px;
padding: 5px 10px;
text-align: center;
font-family: system-ui, sans-serif;
}
.wrapper {
display: flex;
padding: 5px;
background-color: #ccc;
border-radius: 5px;
flex-direction: column;
gap: 5px;
margin: 10px;
max-height: 150px;
/* Control snap from here */
overflow-y: auto;
overscroll-behavior-y: contain;
scroll-snap-type: y mandatory;
}
.wrapper > div:last-child {
scroll-snap-align: start;
}
<div class="wrapper">
<div>01</div>
<div>02</div>
<div>03</div>
<div>04</div>
<div>05</div>
<div>06</div>
<div>07</div>
<div>08</div>
<div>09</div>
<div>10</div>
</div>
You can use the HTML DOM scrollIntoView Method like this:
var element = document.getElementById("scroll");
element.scrollIntoView();
Javascript or jquery:
var scroll = document.getElementById('messages');
scroll.scrollTop = scroll.scrollHeight;
scroll.animate({scrollTop: scroll.scrollHeight});
Css:
.messages
{
height: 100%;
overflow: auto;
}
Using jQuery, scrollTop is used to set the vertical position of scollbar for any given element. there is also a nice jquery scrollTo plugin used to scroll with animation and different options (demos)
var myDiv = $("#div_id").get(0);
myDiv.scrollTop = myDiv.scrollHeight;
if you want to use jQuery's animate method to add animation while scrolling down, check the following snippet:
var myDiv = $("#div_id").get(0);
myDiv.animate({
scrollTop: myDiv.scrollHeight
}, 500);
I have encountered the same problem, but with an additional constraint: I had no control over the code that appended new elements to the scroll container. None of the examples I found here allowed me to do just that. Here is the solution I ended up with .
It uses Mutation Observers (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) which makes it usable only on modern browsers (though polyfills exist)
So basically the code does just that :
var scrollContainer = document.getElementById("myId");
// Define the Mutation Observer
var observer = new MutationObserver(function(mutations) {
// Compute sum of the heights of added Nodes
var newNodesHeight = mutations.reduce(function(sum, mutation) {
return sum + [].slice.call(mutation.addedNodes)
.map(function (node) { return node.scrollHeight || 0; })
.reduce(function(sum, height) {return sum + height});
}, 0);
// Scroll to bottom if it was already scrolled to bottom
if (scrollContainer.clientHeight + scrollContainer.scrollTop + newNodesHeight + 10 >= scrollContainer.scrollHeight) {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}
});
// Observe the DOM Element
observer.observe(scrollContainer, {childList: true});
I made a fiddle to demonstrate the concept :
https://jsfiddle.net/j17r4bnk/
Found this really helpful, thank you.
For the Angular 1.X folks out there:
angular.module('myApp').controller('myController', ['$scope', '$document',
function($scope, $document) {
var overflowScrollElement = $document[0].getElementById('your_overflow_scroll_div');
overflowScrollElement[0].scrollTop = overflowScrollElement[0].scrollHeight;
}
]);
Just because the wrapping in jQuery elements versus HTML DOM elements gets a little confusing with angular.
Also for a chat application, I found making this assignment after your chats were loaded to be useful, you also might need to slap on short timeout as well.
Like you, I'm building a chat app and want the most recent message to scroll into view. This ultimately worked well for me:
//get the div that contains all the messages
let div = document.getElementById('message-container');
//make the last element (a message) to scroll into view, smoothly!
div.lastElementChild.scrollIntoView({ behavior: 'smooth' });
small addendum: scrolls only, if last line is already visible. if scrolled a tiny bit, leaves the content where it is (attention: not tested with different font sizes. this may need some adjustments inside ">= comparison"):
var objDiv = document.getElementById(id);
var doScroll=objDiv.scrollTop>=(objDiv.scrollHeight-objDiv.clientHeight);
// add new content to div
$('#' + id ).append("new line at end<br>"); // this is jquery!
// doScroll is true, if we the bottom line is already visible
if( doScroll) objDiv.scrollTop = objDiv.scrollHeight;
Just as a bonus snippet. I'm using angular and was trying to scroll a message thread to the bottom when a user selected different conversations with users. In order to make sure that the scroll works after the new data had been loaded into the div with the ng-repeat for messages, just wrap the scroll snippet in a timeout.
$timeout(function(){
var messageThread = document.getElementById('message-thread-div-id');
messageThread.scrollTop = messageThread.scrollHeight;
},0)
That will make sure that the scroll event is fired after the data has been inserted into the DOM.
This will let you scroll all the way down regards the document height
$('html, body').animate({scrollTop:$(document).height()}, 1000);
You can also, using jQuery, attach an animation to html,body of the document via:
$("html,body").animate({scrollTop:$("#div-id")[0].offsetTop}, 1000);
which will result in a smooth scroll to the top of the div with id "div-id".
Scroll to the last element inside the div:
myDiv.scrollTop = myDiv.lastChild.offsetTop
You can use the Element.scrollTo() method.
It can be animated using the built-in browser/OS animation, so it's super smooth.
function scrollToBottom() {
const scrollContainer = document.getElementById('container');
scrollContainer.scrollTo({
top: scrollContainer.scrollHeight,
left: 0,
behavior: 'smooth'
});
}
// initialize dummy content
const scrollContainer = document.getElementById('container');
const numCards = 100;
let contentInnerHtml = '';
for (let i=0; i<numCards; i++) {
contentInnerHtml += `<div class="card mb-2"><div class="card-body">Card ${i + 1}</div></div>`;
}
scrollContainer.innerHTML = contentInnerHtml;
.overflow-y-scroll {
overflow-y: scroll;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="d-flex flex-column vh-100">
<div id="container" class="overflow-y-scroll flex-grow-1"></div>
<div>
<button class="btn btn-primary" onclick="scrollToBottom()">Scroll to bottom</button>
</div>
</div>
Css only:
.scroll-container {
overflow-anchor: none;
}
Makes it so the scroll bar doesn't stay anchored to the top when a child element is added. For example, when new message is added at the bottom of chat, scroll chat to new message.
Why not use simple CSS to do this?
The trick is to use display: flex; and flex-direction: column-reverse;
Here is a working example. https://codepen.io/jimbol/pen/YVJzBg
A very simple method to this is to set the scroll to to the height of the div.
var myDiv = document.getElementById("myDiv");
window.scrollTo(0, myDiv.innerHeight);
On my Angular 6 application I just did this:
postMessage() {
// post functions here
let history = document.getElementById('history')
let interval
interval = setInterval(function() {
history.scrollTop = history.scrollHeight
clearInterval(interval)
}, 1)
}
The clearInterval(interval) function will stop the timer to allow manual scroll top / bottom.
I know this is an old question, but none of these solutions worked out for me. I ended up using offset().top to get the desired results. Here's what I used to gently scroll the screen down to the last message in my chat application:
$("#html, body").stop().animate({
scrollTop: $("#last-message").offset().top
}, 2000);
I hope this helps someone else.
I use the difference between the Y coordinate of the first item div and the Y coordinate of the selected item div. Here is the JavaScript/JQuery code and the html:
function scrollTo(event){
// In my proof of concept, I had a few <button>s with value
// attributes containing strings with id selector expressions
// like "#item1".
let selectItem = $($(event.target).attr('value'));
let selectedDivTop = selectItem.offset().top;
let scrollingDiv = selectItem.parent();
let firstItem = scrollingDiv.children('div').first();
let firstItemTop = firstItem.offset().top;
let newScrollValue = selectedDivTop - firstItemTop;
scrollingDiv.scrollTop(newScrollValue);
}
<div id="scrolling" style="height: 2rem; overflow-y: scroll">
<div id="item1">One</div>
<div id="item2">Two</div>
<div id="item3">Three</div>
<div id="item4">Four</div>
<div id="item5">Five</div>
</div>

Change Element style with window height with JavaScript

I'm trying to change the background colour of a div element when the page window height is lower than a certain value using JavaScript. I have a vague idea of how this might work but it doesn't seem to be having any effect.
This is within a tag and loads after the body of my HTML.
<script>
var footer = document.getElementByClassName("footer");
if (window.innerHeight < 800) {
footer.style.backgroundColor = 'black';
}
</script>
Like already mentioned getElementsByClassName returns an array. You had a typo there so nothing was returned, however.
As long as there's only 1 element with the class name "footer" this should work (might be better to use an ID):
<script>
var footer = document.getElementsByClassName("footer")[0];
if (window.innerHeight < 800) {
footer.style.backgroundColor = 'black';
}
</script>
But yeah, you should really look at the dev console when you're writing Javascript. It can save a lot of headaches!
JavaScript does not have a method called getElementByClassName.
The closest thing is getElementsByClassName which returns an HTMLCollection which is an array-like object, so to get the first element in the list you have use an index:
var footer = document.getElementsByClassName('footer')[0];
You can also use querySelector to get the first element with the class name:
var footer = document.querySelector('.footer');
Here is a working example:
var footer = document.getElementsByClassName('footer')[0];
window.onresize = function (event) {
if (window.innerHeight < 800) {
footer.style.backgroundColor = 'black';
} else {
footer.style.backgroundColor = 'blue';
}
}
.footer {
height: 50px;
width: 100%;
background: black;
}
<footer class="footer"></footer>
JSFiddle Demo http://jsfiddle.net/moogs/x63rc6v4/1/

Resize on div element

jQuery has the resize() - event, but it just work with window.
jQuery(window).resize(function() { /* What ever */ });
This works fine! But when I want to add the event to a div element it doesn't work.
E.g.
jQuery('div').resize(function() { /* What ever */ });
I want to start an callback when the size of a div-element has changed. I don't want to start a resizable - event – just a event to check if the size of a div -
element has changed.
Is there any solution to do this?
DIV does not fire a resize event, so you won't be able to do exactly what you've coded, but you could look into monitoring DOM properties.
If you are actually working with something like resizables, and that is the only way for a div to change in size, then your resize plugin will probably be implementing a callback of its own.
I was only interested for a trigger when a width of an element was changed (I don' care about height), so I created a jquery event that does exactly that, using an invisible iframe element.
$.event.special.widthChanged = {
remove: function() {
$(this).children('iframe.width-changed').remove();
},
add: function () {
var elm = $(this);
var iframe = elm.children('iframe.width-changed');
if (!iframe.length) {
iframe = $('<iframe/>').addClass('width-changed').prependTo(this);
}
var oldWidth = elm.width();
function elmResized() {
var width = elm.width();
if (oldWidth != width) {
elm.trigger('widthChanged', [width, oldWidth]);
oldWidth = width;
}
}
var timer = 0;
var ielm = iframe[0];
(ielm.contentWindow || ielm).onresize = function() {
clearTimeout(timer);
timer = setTimeout(elmResized, 20);
};
}
}
It requires the following css :
iframe.width-changed {
width: 100%;
display: block;
border: 0;
height: 0;
margin: 0;
}
You can see it in action here widthChanged fiddle
// this is a Jquery plugin function that fires an event when the size of an element is changed
// usage: $().sizeChanged(function(){})
(function ($) {
$.fn.sizeChanged = function (handleFunction) {
var element = this;
var lastWidth = element.width();
var lastHeight = element.height();
setInterval(function () {
if (lastWidth === element.width()&&lastHeight === element.height())
return;
if (typeof (handleFunction) == 'function') {
handleFunction({ width: lastWidth, height: lastHeight },
{ width: element.width(), height: element.height() });
lastWidth = element.width();
lastHeight = element.height();
}
}, 100);
return element;
};
}(jQuery));
I've created jquery plugin jquery.resize it use resizeObserver if supported or solution based on marcj/css-element-queries scroll event, no setTimeout/setInterval.
You use just
jQuery('div').on('resize', function() { /* What ever */ });
or as resizer plugin
jQuery('div').resizer(function() { /* What ever */ });
I've created this for jQuery Terminal and extracted into separated repo and npm package, but in a mean time I switched to hidden iframe because I had problems with resize if element was inside iframe. I may update the plugin accordingly. You can look at iframe based resizer plugin in jQuery Terminal source code.
EDIT: new version use iframe and resize on it's window object because the previous solutions was not working when page was inside iframe.
EDIT2: Because the fallback use iframe you can't use it with form controls or images, you need to add it to the wrapper element.
EDIT3:: there is better solution using resizeObserver polyfill that use mutation observer (if resizeObserver is not supported) and work even in IE. It also have TypeScript typings.
what about this:
divH = divW = 0;
jQuery(document).ready(function(){
divW = jQuery("div").width();
divH = jQuery("div").height();
});
function checkResize(){
var w = jQuery("div").width();
var h = jQuery("div").height();
if (w != divW || h != divH) {
/*what ever*/
divH = h;
divW = w;
}
}
jQuery(window).resize(checkResize);
var timer = setInterval(checkResize, 1000);
BTW I suggest you to add an id to the div and change the $("div") to $("#yourid"), it's gonna be faster, and it won't break when later you add other divs
There is a really nice, easy to use, lightweight (uses native browser events for detection) plugin for both basic JavaScript and for jQuery that was released this year. It performs perfectly:
https://github.com/sdecima/javascript-detect-element-resize
Only window is supported yes but you could use a plugin for it: http://benalman.com/projects/jquery-resize-plugin/
There now exists Resize Observer
You could use it like so:
const resizeObserver = new ResizeObserver((entries) => {
entries.forEach(console.log);
})
resizeObserver.observe(document.getElementById("ExampleElement"));
For a google maps integration I was looking for a way to detect when a div has changed in size. Since google maps always require proper dimensions e.g. width and height in order to render properly.
The solution I came up with is a delegation of an event, in my case a tab click. This could be a window resize of course, the idea remains the same:
if (parent.is(':visible')) {
w = parent.outerWidth(false);
h = w * mapRatio /*9/16*/;
this.map.css({ width: w, height: h });
} else {
this.map.closest('.tab').one('click', function() {
this.activate();
}.bind(this));
}
this.map in this case is my map div.
Since my parent is invisible on load, the computed width and height are 0 or don't match.
By using .bind(this) I can delegate the script execution (this.activate) to an event (click).
Now I'm confident the same applies for resize events.
$(window).one('resize', function() {
this.div.css({ /*whatever*/ });
}.bind(this));
Hope it helps anyone!
You can change your text or Content or Attribute depend on Screen size:
HTML:
<p class="change">Frequently Asked Questions (FAQ)</p>
<p class="change">Frequently Asked Questions </p>
Javascript:
<script>
const changeText = document.querySelector('.change');
function resize() {
if((window.innerWidth<500)&&(changeText.textContent="Frequently Asked Questions (FAQ)")){
changeText.textContent="FAQ";
} else {
changeText.textContent="Frequently Asked Questions (FAQ)";
}
}
window.onresize = resize;
</script>
document.addEventListener('transitionend', function(e) {
if ($(e.target).is("div")) {
$("div").text("width: "+$("div").width());
}
});
$("div").css({"width":"150px"});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width: 100px;transition-delay: 0.000000001s;">width: 100</div>
A very simple implementation.
<script>
var move = function(e) {
if ((e.w && e.w !== e.offsetWidth) || (e.h && e.h !== e.offsetHeight)) {
new Function(e.getAttribute('onresize')).call(e);
}
e.w = e.offsetWidth;
e.h = e.offsetHeight;
}
var resize = function() {
console.log('Resized')
}
</script>
<style>
.resizable {
resize: both;
overflow: auto;
width: 200px;
border: 1px solid black;
padding: 20px;
}
</style>
<div class='resizable' onresize="resize(this)" onmousemove="move(this)">
Pure vanilla implementation
</div>
If you just want to resize the div itself you need to specify that in css style. You need to add overflow and resize property.
Below is my code snippet
#div1 {
width: 90%;
height: 350px;
padding: 10px;
border: 1px solid #aaaaaa;
overflow: auto;
resize: both;
}
<div id="div1">
</div>

Categories

Resources