简体   繁体   中英

Auto focus to an input when a button is clicked (For AMP articles)

Im new to using AMP and was wondering how I could auto focus to a form input when a button is clicked. But because I can't add script I'm not sure how to approach this. Also I'm using wordpress and the 2 plugins AMP by automattic and Accelerated Mobile Pages by Ahmed Kaludi, Mohammed Kaludi.

this is the button:

<button on="tap:search-icon">
    <i class="icono-search"></i>
</button>

this is the input I want to autofocus:

<input type="text" placeholder="Type here" value="" name="s" id="s" class="user-valid valid">

I tried adding tag to head section but not allowed according to amp validator

Also I came accross this github issue but could not find anything to help me figure it out.

Cheers

You can partially solve this problem with HTML and using an <a> and an internal href instead of a button.

 .button-link { display: inline-block; padding: 6px 14px; background-color: rebeccapurple; color: white; border-radius: 5px; text-decoration: none; font-family: sans-serif; } 
 <a href="#s" class="button-link" on="tap:search-icon"> <i class="icono-search"></i> Search </a> <p>Click the button or scroll down to see the input</p> <p>Lorem ipsum</p> <p>Lorem ipsum</p> <p>Lorem ipsum</p> <p>Lorem ipsum</p> <input type="text" placeholder="Type here" value="" name="s" id="s" class="user-valid valid"> 

In Chrome on desktop and Android it works exactly as you need it to.

All major browsers scroll the input element into view after clicking the link. In Chrome it moves the focus and the text caret appears. In Safari on desktop and iOS focus is moved to the input, but the text caret does not appear. In Firefox it only scrolls to the input but it neither highlights nor shows the caret.

I understand this does not fully resolve your issue, but depending on your use case and which browsers you need to support, this might be better than alternatives. If you like, make a feature request issue on the AMP Project GitHub to add a global focus action, similar to the existing hide and show actions . If you are motivated to write the feature yourself, feel free to contribute to the AMP Project. You can implement the solution and create a pull request for review. I hope this has helped you!

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