Ph Abd Ph Abd - 5 months ago 8
jQuery Question

jquery call one script from another

this is part of code from online shop page. php code loads full catalog, after that jquery clicks on corresponding link and filters catalog.

i have two jqueries on a page and both of them work, BUT

<script>
$(document).on('click', '.side-menu-categories li', function () {
var click = $(this).attr('data-filter');
$('.product-box').hide();
$('.product-box').each(function () {
if ($(this).attr('data-filter') == click || click == 0) {
$(this).fadeIn('fast');
}
});
});
</script>


this part is working good and i have no problem with it, but when i try to call it on window load it's not working

$(window).load(function () {
$('#loader_spin').hide();
$('#product_container').show();
var clicked = false;
var filter_catalog = <?php echo(isset($_GET['id']) ? $_GET['id'] : 0); ?>;
$('.side-menu-categories li').each(function () {
if ($(this).attr('data-filter') == filter_catalog) {
$(this).click();
var clicked = true;
}
});
if (clicked == false) {
$('.side-menu-categories li[data-filter="0"]').click();
}
});

Answer

With var clicked = true; you are defining new variable into local scope of each() function, so remove var (i.e. just do clicked = true) in order to use global variable defined in load() scope above:

$(window).load(function () {
    $('#loader_spin').hide();
    $('#product_container').show();
    var clicked = false;
    var filter_catalog = <?php echo(isset($_GET['id']) ? $_GET['id'] : 0); ?>;
    $('.side-menu-categories li').each(function () {
        if ($(this).attr('data-filter') == filter_catalog) {
            $(this).click();
            clicked = true; //don't declare it locally
        }
    });
    if (clicked == false) {
        $('.side-menu-categories li[data-filter="0"]').click();
    }
});