简体   繁体   中英

Refresh javascript onclick

i'm trying to refresh a javascript i created that set height on my div when page load.

<script>
    jQuery(function($) {
        $('#bloc2').height($('#zonetexteposition').height());
        $('#bloc2-vertical').height($('#zonetexteposition').height());
        $('#bloc2-horizontal').height($('#zonetexteposition').height());
    });
</script>

Until now, everything works fine. my divs are getting the right height from div #zonetexteposition.

The thing is, it calculate the height of the page only onload. My FAQ page have questions in it and the anwser appear on click of the question, so it change the height of my div #zonetexteposition. Since the javascript only run onload it doesnt resize to the new height of #zonetexteposition. So i would like to know if its possible to make a script that gonna refresh the above script onclick of a question.

Thanks, hope it's clear

将您完成的所有代码包装到一个函数中,然后,在页面加载时,调用该函数,每当您单击所需的元素时,都调用同一函数。

Create a function that has the calculations:

function foo () {
    $('#bloc2').height($('#zonetexteposition').height());
    $('#bloc2-vertical').height($('#zonetexteposition').height());
    $('#bloc2-horizontal').height($('#zonetexteposition').height());
}

Add an event listener to the button:

$("button").on('click', function(event) {
   foo();
   //anything you want on the click also
});

Call the function on load:

jQuery(function($) {
    foo();
});

One quick answer would be : instead of calculating height everytime, just set the min-height instead of height on DOM load .

Like that :

$('#bloc2, #bloc2-vertical, #bloc2-horizontal').css('min-height',$('#zonetexteposition').height());

So you wouldn't have to recalculate height of the container after the DOM load, as the container would handle it "naturally" it it gets bigger.

Tout simplement :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM