Search code examples
javascripthtmlformsinputtext

How can I recommend a text when user focus on an input


I have a search box in my page, and I want to recommend some part of my page, when user focus on my search box input, to write something

<input type="text" placeholder="Search...">

I want to recommend the user: Best phones , best 2021 laptops etc...


Solution

  • You could catch the "click" event on this field via JQuery (if you can use JQuery) and then show the recommendations.

    If the recommendations are fixed text that you don´t need to have in a database, you can have them in a hidden div, and when the user clicks on the search box, turn the div into visible.

    Very basic code example with JQuery:

    <html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    </head>
    <body>
        <form>
            <input type="text" placeholder="Search..." id="myAmazingSearchBox">
        </form>
    
        <div id="recommendations" style="display:none">
            <p>Best phones , best 2021 laptops etc...</p>
        </div>
    
        <script type="text/javascript">
            $("#myAmazingSearchBox").click(function() {
                $("#recommendations").fadeIn();
            });
        </script>
    </body>