Set width and height of a DIV based on another div - javascript

How do I set width and height of a DIV based on another div?
This is how I've done it but it works only when the alert is present??
var readyC = setInterval(function() {
if (Condition) {
$('#divAA').width($('#divBB').width()).height($('#divBB').height());
//alert($('#divBB').width()) // works when this is uncommented??
}
clearInterval(readyC);
}, 10);
EDIT:
Fixed typo:
$('#divBB'+i) to $('#divBB')

The reason why you're getting it only when you keep an alert is, you're using setInterval with such small interval of 10ms.
When you use alert, the execution is stopped and that's why you see the div resized. You must increase the interval to a higher value.
Also clearInterval is not inside else block, So it means what the timer will clear on first attempt itself. In that case you don't need a setInterval at all.
Update based on comments
As you're looping through a list of divs to update the height of other divs, you must use self invoking function to bind the value of i correctly.

If the content of your divs are loaded dynamically, then you will need to use window.load event to get its correct height as discussed here: https://stackoverflow.com/a/13071846/1845408
$(window).load(function() {
$('#divAA').width($('#divBB').width()).height($('#divBB').height());
});

Related

finding the div height always return zero jquery

I am using jquery to find div's height, but it always returns zero. I can clearly see the height of the div in chrome's inspect element css window.
<div class="findheight">some text here</div>//original height is 21px
But when i do the following it returns zero:
$('.findheight').height() //it always returns zero. really making me sick
So I thought div might not have text when i call height method on it and i did like below.
if($('.findheight').text().length > 6){
alert($('.findheight').height());//This also returns zero so weird
}
I also tried by setting windows.timeoutcall, but that does not help with any delay time.
Can any one help me why I am always getting zero?
If the content of your divs are loaded dynamically, then you will need to use window.load event to get its correct height as discussed here: https://stackoverflow.com/a/13071846/1845408
$(window).load(function() {
alert($('.findheight').height());
});
Copied your code into jsfiddle, the height is 18
<div class="findheight">some text here</div>//original height is 21px
alert($('.findheight').height());
Did you wrap your jquery in a function that executes when the dom is ready?
$(document).ready(function(){
console.log($('.findheight').height());
});
It works for me otherwise your error may be browser specific.
Here is a jsfiddle of it working. Just check your console.
https://jsfiddle.net/lesshardtofind/vzxd4t57/
If for some reason you wouldn't have access to the element on document ready, such as working in dynamically templated frameworks like Meteor, Ember, React, or Angular then each object has a hook to register your functions in.
If otherwise you were trying to get access to an element in between transitions you could set a interval.
var interval;
var timeout = setTimeout(function(){
clearInterval(interval)
}, 10000); // destroy interval after 10 seconds to prevent memory leak
interval = setInterval(function(){
if($('.findheight').length > 0){
// execute your code here because you know this element is in the dom
clearInterval(interval);
clearTimeout(timeout);
// clear both timeout and interval
}
}, 100); // loop every 100 milliseconds to "poll" for the node in the dom
Try doing this:
$('div.findheight').height();
The .height() takes exactly CSS's height property.
If it's a dynamic content you have to handle this in the respective event..
For example:
If you're working with the content on page load like #renakre said, use $(window).load() or $(document).load() to trigger the call.
If it's a content generated from some other process you have coded, you have to bind respective event.. let's presume it's a click or on:
$(document).load(function() {
// Shows the height on page load
console.log($('.findheight').height());
$('#another-element-ID').click(function() {
// .. code which populate the div dynamicaly
// Shows the height
console.log($('.findheight').height());
});
$('.another-element-class').on('change', function() {
// .. code which populate the div dynamicaly
// Shows the height
console.log($('.findheight').height());
});
});
Hope this can help you.
This happens when an explicit height/width is not set for that element OR when the CSS for inner/outer elements set the height/width to 0;
To get height/width like this you have to explicitly set height/width.

Dynamic SVG animation only works once

I have this animation setup to indicate which SVG was selected. The animation adds a svg:use element, and 3 animate or animateTransform elements within the svg:use element. Thanks to some great help here on SO I was able to get this working properly.
My new problem however is that the animation only works once as designed once. If a second element is selected, the animation appears to try to take place, as you can see the stroke-width increase, but the scale doesn't happen.
I thought this would be a simple fix by using a setTimeout to call a function and remove the svg:use after the animation completed. I wasn't so lucky.
An example of my problem can be seen here: http://codepen.io/JoeyCinAZ/pen/GHhbw
The function I wrote to remove the animation is here
setTimeout( function() {removeAnimation(objID)}, 5000);
function removeAnimation(objID) {
var useEl = document.getElementById(objID);
useEl.nextSibling.remove();
}
You've two issues within the animation. The simplest is duration, it can't per the SVG specification begin with a . so
flash.setAttributeNS(null, 'dur', '.5s');
is strictly speaking not valid and Firefox rejects it. I believe there are plans to change the SVG specification to match Chrome's laxer behaviour but until that happens write it as
flash.setAttributeNS(null, 'dur', '0.5s');
Secondly your main issue is that once you run the animation the document timeline goes from 0 to 5.5 seconds (that's how long all your animations take). The next time you create the animation, the document timeline is therefore at 5.5 seconds and the initial animation doesn't run because it's in the past as it's supposed to start at 0s. You could solve this either by
a) calling setCurrentTime to reset the timeline to 0, or
b) having the initial animation trigger from the button press event.
I had a similar issue before and solved it by completely removing the content of the element that contains the generated SVG, and then simply reload the new SVG in the empty element.
Instead of using a setTimeout which make the whole thing a bit weird, I would simply call it on clicking the element selector:
var elem = document.getElementById('myElementSelector');
elem.addEventListener('click', function() {
document.getElementById(surroundingElementID).innerHTML = "";
//Check what has been clicked and call function that creates the SVG on the surroundingElementID
}, false);

Javascript - Possible to check if an interval is already set?

I have a div that is bouncing every 5 seconds using an interval.
When scrolling to the bottom of the page, this div fades out and the interval is cleared.
However, I think there is an issue with the interval being created multiple times and overlaps upon itself.
Is there a way to check if an interval is set, and if so clear it, and if not, to set it?
The reason I need to clear the interval is because the bounce effect of jquery causes the div to appear again even if it's hidden.
JSBIN: http://jsbin.com/ijuhok/4/
Seems that you set the interval whenever it is scrolled. So if I scroll down, and then scroll down again you set it twice.
Just clear it before hand every time you set it and you should be ok.
http://jsbin.com/ijuhok/6
You need to overwrite the existing interval so that you can clear it from everywhere: http://jsbin.com/ijuhok/5/.
$j("#more").fadeIn('slow',function(){
ResInterval = window.setInterval(bounceMore, 5000);
// no "var"
});
You can eliminate $(document).ready for window because it's always available.
Your issue is that you're defining ResInterval in a local scope, because you've used var:
$j("#more").fadeIn('slow',function(){
var ResInterval = window.setInterval('bounceMore()', 5000);
});
Remove the var prefix, and your code will work as expected: Currently, ResInterval is a local varibale of the callback function in fadeIn. When var is omitted, the interval will be assigned to the closest ResInterval declaration (using var).
I did this like below, My problem was solved. you should set the value like "false", when you clearTimeout the timer.
var timeer=false;
----
----
if(timeer==false)
{
starttimer();
}
-----
-----
function starttimer()
{
timeer=setInterval(activefunction, 1000);
}
function pausetimer()
{
clearTimeout(timeer);
timeer=false;
}

How to use javascript to monitor a change in a div value?

I have a page with a countdown in a DIV with id ="count"
I would like to monitor this div value so, when it reaches 0, a alert pops up.
I've gono so far as
if(parseInt(document.getElementById('count').innerHTML) < 2){}
But I don't know how to "listen" for the div changes
Can anyone help me?
Btw: it needs to be in pure javascript, with no such things as jquery.
Update:
I have no say so in the original code. It's an external page and I'm trying to run this code at the address bar
Presumably you have a function running based on setInterval or setTimeout. Have that function call your function when it gets to zero.
If you can't do that, you can try optimised polling - use setInterval to read the value, estimate when it might be near zero, check again and estimate when it might be zero, etc. When it is zero, do your thing.
There are DOM mutation events, but they are deprecated and were never well or widely supported anyway. Also, they are called when content changes so probably too often for your scenario anyway.
If you are changing the value of #count yourself then call the alert from that place. If not use:
window.setInterval(function(){
if(parseInt(document.getElementById('count').innerHTML) < 2) alert('Alarm!');
},1000); // 1s interval
UPDATE
To clear that interval:
var timer = window.setInterval(function(){
if(parseInt(document.getElementById('count').innerHTML) < 2) {
alert('Alarm!');
window.clearInterval(timer);
}
},1000); // 1s interval
//or by using non-anonymous function
function check(){
if(parseInt(document.getElementById('count').innerHTML) < 2) {
alert('Alarm!');
window.clearInterval(timer);
}
}
var timer = window.setInterval(check,1000);
The only efficient way to monitor this is to go to the code that is actually changing the div and modify it or hook it to call a function of yours whenever it updates the contents of the div. There is no universal notification mechanism for anytime the contents of div changes. You will have much more success looking into modifying the source of the change.
The only option I know of besides the source of the change would be using an interval timer to "poll" the contents of the div to notice when it has changed. But, this is enormously inefficient and will always have some of inherent delay in noticing the actual change. It's also bad for battery life (laptops or smartphones) as it runs continuously.
You don't listen for the div to change. The div is just there for a visual representation of the program's state.
Instead, inside whatever timing event is counting down the number, use a condition such as...
if (i < 2) {
// ...
}

Reload the page just once if a div is above certain position

I want to reload the page only once if a given div is positioned higher than position:absolute; top:15%.
I think this could be done with jQuery's .css method, something like:
if ('#mydive').css('top') > '15%' {
//reload the page
}
Could someone suggest a simple solution, preferably jQuery or pure JavaScript?
If what you meant is the top of the document, you can probably try:
var percent = .15; // 15%
if ($('#yourdiv').offset().top > ($(document).height() * percent)) {
window.location.reload();
}
// if by pixels
var pixels = 10; // 10px
if ($('#yourdiv').offset().top > pixels) {
window.location.reload();
}
You can check the current position of a div using the Computed Style
If you are have a like an animation or a drag and drop, you can use the onmousemove event to track the position of the div. but be careful the mousemove will be trigger for every pixel it moves and it my use lots of process time, so be wise on how you use it :)
Well, it is rather hard to say how you should determine the position of the div since you presented no code, but basically you should write a function that fetches the window height and the offset of the div relative to the top of the window to determine whether it is higher than 15%. You then need to call this function every time using the window.onscroll event listener. When the function returns true, trigger trigger window.location.reload(true) to reload the page. I imagine this could be done fairly easily in jQuery as well.
the above answers point you in the right way, but in order to "reload the page only once", you need an extra ingredient. you need a way to store a flag that points out whether the page has already been reloaded or not.
Say you follow tradyblix's code.
You should check for that flag before reloading your page :
if (hasReloaded() && $('#yourdiv').offset().top > ($(document).height() * percent)) {
reload();
}
where hasReloaded is a function that determins if the page has been reloaded, and it can be either a function that sends an ajax request to a server, that checks a cookie or even the localStorage object:
function hasReloaded(){
return !!localStorage['reloaded'];
}
In order to set that flag, your reload function needs to access the localStorage (or cookie or ajax server response) :
function reload(){
localStorage['reloaded'] = true;
window.location.reload();
}
This is just a sketch of how you should write this functionality.

Categories

Resources