Reputation: 333
I'd like to make a link to a input. My current link example works (takes me to the area where the id is set) but what I really want is when a user clicks on the link to take him exactly to the input, being able to type right away.
<input type="text" id="search" name="search">
<a href="#search">
<img src="http://www.example.com/images/something.jpg" alt="">
</a>
Is this even achievable without JQuery/JavaScript? Please post solutions in any method you can imagine. Been searching for this for a while and couldn't find an answer.
Upvotes: 0
Views: 125
Reputation: 123397
No need to use javascript: use a label
instead of a link with the for
attribute
<input type="text" id="search" name="search">
<label for="search">
<img src="http://www.example.com/images/something.jpg" alt="something">
</label>
if you also need a smooth page scroll animation, in order to reach the top offset of the input element, you can instead use a script, e.g.
Codepen Example: http://codepen.io/anon/pen/VLyOqg
$(function() {
$('label[for]').on('click', function(evt) {
evt.preventDefault();
var inputId = "#" + $(this).attr('for');
$('html:not(:animated), body:not(:animated)').animate({
scrollTop: $(inputId).offset().top
}, 600, function() {
$(inputId).focus();
});
});
});
Upvotes: 13
Reputation: 8513
Use jQuery focus!
$('[href="#search"]').click(function(){$('#search').focus();});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search" name="search">
<a href="#search">
<img src="http://www.example.com/images/something.jpg" alt="">
</a>
Upvotes: 1
Reputation: 2229
<script>
function setFocus(){
elm = document.getElementById("search");
jump(elm);
elm.focus();
}
function jump(elm){
var top = elm.offsetTop; //Getting Y of target element
window.scrollTo(0, top); //Go there.
}
</script>
...
<a href="javascript:setFocus('search')">
<img src="http://www.example.com/images/something.jpg" alt="">
</a>
Upvotes: 2