简体   繁体   中英

jQuery Click Event only works in Landscape (iPhone)

I have been asked to patch up a rather badly written responsive website at work, and have been left stumped by an issue with a jQuery click event.

The event works fine on iPhone in Landscape mode, but in Portrait mode it doesn't do anything.

Here's the jQuery:

if (width <= 480) {
    function menu(e) {
        e.PreventDefault();
        $('#menu-item-93 .sub-menu').slideToggle('fast');
    }

    $('.nav-cont').addEventListener('click', menu(e));
    $('.nav-cont').addEventListener('touchstart', menu(e));
}

And the section thats relevant from the header.php file (did I mention, this is a Wordpress site)

<nav id="main" class="main clearboth">
    <?php 
        wp_nav_menu( array( 
            'sort_column' => 'menu_order', 
            'theme_location' => 'primary', 
            'after'=>'<img src="'.template_url('images/button/link-445x68.png').'" class="show-480" />'
        ) );
    ?>
</nav>
<div class="nav-cont">
    <div class="nav-text show-480">NAVIGATION</div>
    <img class="nav-button show-480" src="<?php echo template_url('images/button/navigation-closed-nt-445x52.png');?>" />
</div>

Anyone have any idea why this touch event only fires in landscape mode?

Your code starts with if (width <= 480) { . This looks like it can be valid portrait but not in landscape, making the problem right there.

These lines:

$('.nav-cont').addEventListener('click', menu(e));
$('.nav-cont').addEventListener('touchstart', menu(e));

should be:

$('.nav-cont').addEventListener('click', menu);
$('.nav-cont').addEventListener('touchstart', menu);

or even:

$('.nav-cont').on('click', menu);
$('.nav-cont').on('touchstart', menu);

The current code adds the result of calling the menu function to the event handler.

This was solved in the end by going through multiple javascript files left by the old development agency who were working on the site. I found that there were multiple instances of click handlers on this selector which were contradicting each other. I removed the others and bam, it worked.

It even worked in the way I originally intend for it to work with a basic

$('.nav-cont').click(function() {
});

event handler.

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