简体   繁体   中英

focus() doesn't work with anchor link

<a id="news_click" href="#news"> <span style="color:#B2B2B2" class="radius secondary label">Do you want fresh news and feeds?</span></a>

<div class="large-5 columns">
    <div class="row collapse">
        <div class="small-12 columns">
            <form id="email_form" data-validate="parsley" data-trigger="focusin focusout">
                </br>
                <input id="email" type="text" placeholder="Email" class="hg" name="email" data-notblank="true" data-type="email">
            </form>
        </div>
    </div>
</div>

<div class="bottom_blue" id="news"></div>

$('#news_click').click(function () {
    $('form#email_form input#email.hg').focus();
});

The focus event only works if i remove the <div class="bottom_blue" id="news"></div . This is not an option since this is an anchor link.

Any idea? Probably the problem is that js is executed before the anchor.

EDIT: Apparently this works in chrome, not in FF.

demo

Essentially you need to account for the click event and focus as a race condition in Firefox. Use either:

$('#news_click').click(function (e) {
    e.preventDefault();
    $('#email').focus();
});

or

$('#news_click').click(function (e) {
    setTimeout(function(){$('#email').focus();},10);
});

jsFiddle example

You forgot an angle bracket at the end of <div class="bottom_blue" id="news"></div ...

Demo here

Use this instead:

<div class="bottom_blue" id="news"></div>

Also, try changing this:

$('form#email_form input#email.hg').focus();

To this:

$('#email').focus();

There can only be one element with the same id anyway, so it makes no difference how specific you are.

EDIT: Firefox seems to visit the href after the email box is focused... You can either use preventDefault() as in j08691's answer, or take the href attribute off the link (see the updated fiddle ).

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