jQuery script not being refreshed - javascript

I have been wondering why the following jquery script is not beeing run every 5 seconds.
The correct height of the DIV ".leistung" (there are multiple ".leistung" div's with different lenght of text thats why every block has to have the same height) is beeing applied on load. But the function is not beeing run every five seconds for some reason.
Does anyone know why this is happening?
<section class="leistung">
<div class="leistung-image">
<img src="http://www.myfico.com/Images/sample_overlay.gif"/>
<div class="leistung-image-titel">
<span>Title</span>
</div>
</div>
<div class="leistung-teaser">
Some more text
</div>
</section>
<script>
var maxHeight = 0;
window.setInterval(function(){
$('.leistung').each(function(){
var thisH = $(this).height();
if (thisH > maxHeight) { maxHeight = thisH; }
});
$('.leistung').height(maxHeight);
}, 5000);
</script>

Since the OP is looping using each and since there are no any other elements with the class name leistung, I don't think he wants only to take the <section class="leistung"> element. So I assume that he want to select all the elements with name starting leistung.
<script>
var maxHeight = 0;
window.setInterval(function(){
//added ^ selector here
$("[class^=leistung]").each(function(){
var thisH = $(this).height();
if (thisH > maxHeight) { maxHeight = thisH; }
console.log(maxHeight);
});
// and here
$("[class^=leistung]").height(maxHeight);
}, 1000);
</script>

I found my problem. I only run the fuction every 5 seconds. But when the height has been set once it will just fetch the set height again and set it again...
I will have to come up with something else to solve my problem

Related

Setting div class width to the widest div is not updating

I have a list of elements that content is generated with php from a database (I can multiply their values). I want them to have the width of the widest element - it should be updated on page load and click on select tag (multiplying the values). The script works on page load, but it's not updating the width when I'm clicking the select tag. Also, when the widest element shrinks, the width is not shrinking as it should, but staying the same as before.
<head>
<script src="script.js" defer></script>
</head>
<select class="multiply_ing">
<option value="0.5">0.5x</option>
<option value="1" selected>1x</option>
<option value="5">5x</option>
<option value="10">10x</option>
</select>
// it looks like this - data-val generated from php <p class='ing_wght' data-val='$ing_weight'></p>
<p class='ing_wght' data-val='33'></p>
<p class='ing_wght' data-val='54'></p>
<p class='ing_wght' data-val='7312'></p>
<p class='ing_wght' data-val='6'></p>
// js/jquery code for multiplying is in the same file (above this one) as the script to change the width
$(".multiply_ing").on("click", function(){
ingWidth();
});
$(window).on("load", function(){
ingWidth();
});
function ingWidth(){
let maxWidth = 0;
let widestIngWght = null;
let ingWght;
$(".ing_wght").each(function(){
ingWght = $(this);
if(ingWght.width() > maxWidth){
maxWidth = ingWght.width();
widestIngWght = ingWght;
}
});
$(".ing_wght").css("width", maxWidth);
console.log(maxWidth);
}
How can I fix these problems?
Change:
$(".multiply_ing").on("click", function(){
ingWidth();
});
To:
$(document).on("change", ".multiply_ing", function(){
ingWidth();
});
This should work.
So I found the solution. I had to add an if statement that removes the width from the class $(this) if it's wider or equal to previously defined max width.
$(".multiply_ing").on("click", function(){
ingWidth();
});
$(window).on("load", function(){
ingWidth();
});
function ingWidth(){
let maxWidth = 0;
let widestIngWght = null;
let ingWght;
$(".ing_wght").each(function(){
ingWght = $(this);
if(ingWght.width() >= maxWidth){
ingWght.width("");
}
if(ingWght.width() > maxWidth){
maxWidth = ingWght.width();
widestIngWght = ingWght;
}
});
$(".ing_wght").css("width", maxWidth);
}
Maybe it will help someone in the future.

Change div to visible after initial load?

I have an issue where a div is loaded before the javascript, which displays the text, and after the javascript is loaded it will display it differently (autoscrolling). To prevent this I tried adding visibility: hidden; to the div #vs, and then add the following code to the jQuery document.getElementById("vs").style.visibility= "visible";
This solves the problem, but after 3 seconds it will disappear, and after 3 seconds it will reappear, and it keeps going like this. How do I prevent this?
jQuery(document).ready(function($) {
function autoRefresh() {
$.ajax({
success: function(data) {
// Find div id #vs
var result = $('<div />').append(data).find('div#vs').html();
$('div#vs').html(result);
document.getElementById("vs").style.visibility= "visible";
// If div id #vs takes up more than 85% of inner height, add class .vscroll
if (document.getElementById('vs').clientHeight > window.innerHeight * 0.85)
$('div#vs').addClass('vscroll');
// If div id #vs takes up less than 85% of inner height, remove class .vscroll
if (document.getElementById('vs').clientHeight < window.innerHeight * 0.85)
$('div#vs').removeClass('vscroll');
}
});
}
autoRefresh();
// Refresh at page load and every 3000 milliseconds / 3 seconds
var auto_refresh = setInterval(autoRefresh, 3000);
})
I am not a JQuery expert, but I think it's because you are using getElementById() instead of a JQuery selector.
I think you need to do this:
$('div#vs').attr('style','visibility: visible');
Forgive me if the JQuery code isn't perfect, I haven't tried to run it

scroll to div ajax/javascript

Ok, for the life of me, I can't get this to work. I've searched for examples and I found tons. But none of them seem to work for me.
Question is simple, I have a div that loads content from the database.
I need to scroll to the bottom of the div when the page is loaded.
here's an example.
<body>
<div id="container">
<div id="messagewindow">
<?php
foreach($results as $r){
//content loop..
}
?>
<div id="scrolltome"></div>
</div>
</div>
</body>
I added the div id scrolltome in hopes it would work.
Thank you in advance!
Try using window.scrollTo(0, $(element).offset().top)
For example: https://jsfiddle.net/88uhpkx0/
Try below function
function scrollToElement(selector, time, verticalOffset) {
time = typeof(time) != 'undefined' ? time : 500;
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $(selector);
offset = element.offset();
offsetTop = offset.top + verticalOffset;
$('html, body').animate({
scrollTop: offsetTop
}, time);}
Call this function by
scrollToElement('#scrolltome`, 750, -50); . Here 750 time set for animate and -50 is elements offset value. You can change these values according to your needs
Simply pass the top offset distance of #scrolltome div to body scrollTop on window load like this:-
$(window).load(function(e) {
var distance = $('#scrolltome').offset().top
$('html,body').animate({scrollTop:distance},1500);
});
First of all, your scrolltome div is missing >.
And you could try the following to make the scroll.
$('#messagewindow').animate({
scrollTop: divHeight
}, 1000);

How can I have two of these on one page with different variables? (JQuery)

I need to have 2 of these one page but each with different percentages. When I try re-writing the JS or even use different class/ID names it still always pulls from the first SPAN.
http://jsfiddle.net/K62Ra/
<div class="container">
<div class="bw"></div>
<div class="show"></div>
<div id="bar" data-total="100">
<div class="text">Currently at <br/><span>70</span><br><i>Click To Give</div>
</div>
JS and CSS in the Fiddle.
Much Thanks.
This one will work smoothly:
http://jsfiddle.net/K62Ra/7/
$('.bar').each(function() {
var percentStart = 0;
var total = $(this).data('total');
var percent = parseInt($(this).find('span').html());
$(this).find('> div').addClass("load");
var that = this;
var timer = setInterval(function() {
$(that).siblings('.show').css('height', percentStart/total*100+'%');
$(that).css('height', percentStart/total*100+'%');
$(that).find('span').html('%'+percentStart);
if(percentStart<percent) { percentStart=percentStart+1; return; }
clearInterval(timer);
}, 35);
});
The interval has to be terminated as well, or it will run infinitely (though not doing anything).
I've changed your id="bar" into a class. Then I'm running a each loop for the .bar classes. here is the fiddle: http://jsfiddle.net/K62Ra/3/
here is the code:
$('.bar').each(function (index, element) {
percent = $(this).find('span').html();
total = $(this).attr('data-total');
percentStart = 0;
setInterval(function () {
$('.show').css('height', percentStart / total * 100 + '%');
$(this).css('height', percentStart / total * 100 + '%');
$(this).find('span').html('%' + percentStart);
if (percentStart < percent) {
percentStart = percentStart + 1;
}
}, 35);
});
$(".bar div").addClass("load");
Like some of the comments have stated, having duplicate ids is bad design and can cause some weird errors.
You can find a solution to your problem by changing a number of things. One, instead of
referring to divs in you selectors by id'#', you can infer them by class '.' like
$('.bar')
The next step would be to ensure exclusivity for each div with class 'container' by using a closure
$('.container').each(function(){
var x
var y
.
.
});
And finally, avoid 'selecting' elements in the selector directly, but use $(this) and .find() to ensure you are within the current div with class 'container'.
http://jsfiddle.net/K62Ra/5/
$('.container').each(function(){
var percent = $(this).find('div.bar div span').html();
var total = $(this).find('div.bar').attr('data-total');
var percentStart = 0;
var that = $(this);
setInterval(function() {
that.find('.show').css('height',percentStart/total*100+'%');
that.find('div.bar').css('height',percentStart/total*100+'%');
that.find('div.bar div span').html('%'+percentStart);
if(percentStart<percent) {percentStart=percentStart+1;}
},35);
$(this).find("div.bar div").addClass("load");
});
There are already several good answers here. I would recommend validating your html. Also some of your css was causing weirdness when there was scrolling involved (fixed background images weren't scrolling.)
I took a slightly different approach than everyone else. Instead of using a setInterval I went with $.animate and a step function. Like others, I chose a class to target each of the items: 'fill-me-up'.
Fiddle: http://jsfiddle.net/LFbKs/6/
NOTE: Check the fiddle since I modified the HTML (very slightly) and the css to a larger degree.
// for each item we need to "fill up"
$('.fill-me-up').each(function(){
// cache DOM references
var this$ = $(this)
, bar$ = this$.find('.bar')
, show$ = this$.find('.show')
, span$ = bar$.find('div span')
// the target percentage height for this item
, p = span$.text()
// combine '.bar' and '.show' so we can apply the animation to both
, toAnimate = $().add(bar$).add(show$);
// add class causing fade-in
bar$.find('div').addClass('is-visible');
// animate height to target height over 2 seconds and
// at each step, update the span with a truncated value
toAnimate.animate(
{ height: p+'%' },
{
duration: 2000,
step: function( currentStep ) {
span$.html('%'+currentStep.toFixed(0));
}
}
);
});
Cheers

How to make div text fade in

I am using javascript to make text inside a div fade in on page load. It seems to work but most times the text initially shows on page load for about half a second, disappears and then fades in like it's supposed to. I've tried moving the javascript into the header, above body tag and below /body tag. It always runs the same. Thanks.
<body onload="javascript:ShowDiv('Layer63');">
<div id="Layer63" class="style1z">
<span class="style16">“Line 1 of fade in text"<br />
“Line 2 of fade in text"</span><br />
-<span class="style12">“Line 3 of fade in text"</span></div>
</body>
<script>
function ShowDiv(name){
//duration of transition (1000 miliseconds equals 1 second)
var duration = 1500;
// how many times should it should be changed in delay duration
var AmountOfActions=30;
var diiv= document.getElementById(name);
diiv.style.opacity = '0'; diiv.style.display = 'block'; var counte=0;
setInterval(function(){counte ++;
if ( counte<AmountOfActions) { diiv.style.opacity = counte/AmountOfActions;}
},
duration / AmountOfActions);
}
</script>
Try putting these css attributes:
#Layer63 {
opacity: 0;
display: none;
}
Since you're animating opacity from 0 anyway and set ur display to block with js why not have them hidden at pageload?
Have you considered using the fadeIn() method in jQuery?
$(document).ready(function() {
$("#Layer63").fadeIn(1000);
});
Or you could pull the code from there, if you want to use pure JavaScript:
http://youmightnotneedjquery.com/

Categories