How to create a search box?

Asked

Viewed 2,094 times

2

I wish to put on my website a search box of words and I don’t know how to do it, I’ve tried several examples and none worked!
I need this search box because my site is very extensive and would facilitate users.

Ps.: I will not paste my html code here because it is too long (8304 lines), unless it is necessary, then here is my code and here my website.

I’m sorry but I’m new and very lay!

  • The page is static ? Like its content will follow the same in html or has some function to add text? php or javascript

  • Static, if I understand the question!

  • What would be a "word search box"? It’s a text field that if I type something should happen what?

  • I meant as "word search box" as the "Ctrl+F" of the browser, which makes a word search!

2 answers

1


This will be the way you mentioned in the comment using the same API mark.js, I left the 2 answers because they can help other people, see in the documentation that it is possible to do a lot of things. Documentation mask.js.

$(function() {

  // the input field
  var $input = $("input[type='search']"),
    // clear button
    $clearBtn = $("button[data-search='clear']"),
    // prev button
    $prevBtn = $("button[data-search='prev']"),
    // next button
    $nextBtn = $("button[data-search='next']"),
    // the context where to search
    $content = $(".content"),
    // jQuery object to save <mark> elements
    $results,
    // the class that will be appended to the current
    // focused element
    currentClass = "current",
    // top offset for the jump (the search bar)
    offsetTop = 50,
    // the current index of the focused element
    currentIndex = 0;

  /**
   * Jumps to the element matching the currentIndex
   */
  function jumpTo() {
    if ($results.length) {
      var position,
        $current = $results.eq(currentIndex);
      $results.removeClass(currentClass);
      if ($current.length) {
        $current.addClass(currentClass);
        position = $current.offset().top - offsetTop;
        window.scrollTo(0, position);
      }
    }
  }

  /**
   * Searches for the entered keyword in the
   * specified context on input
   */
  $input.on("input", function() {
  	var searchVal = this.value;
    $content.unmark({
      done: function() {
        $content.mark(searchVal, {
          separateWordSearch: true,
          done: function() {
            $results = $content.find("mark");
            currentIndex = 0;
            jumpTo();
          }
        });
      }
    });
  });

  /**
   * Clears the search
   */
  $clearBtn.on("click", function() {
    $content.unmark();
    $input.val("").focus();
  });

  /**
   * Next and previous search jump to
   */
  $nextBtn.add($prevBtn).on("click", function() {
    if ($results.length) {
      currentIndex += $(this).is($prevBtn) ? -1 : 1;
      if (currentIndex < 0) {
        currentIndex = $results.length - 1;
      }
      if (currentIndex > $results.length - 1) {
        currentIndex = 0;
      }
      jumpTo();
    }
  });
});
mark {
  background: orange;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/mark.js/7.0.0/jquery.mark.min.js"></script>
<div class="header">
  Pesquisar:
  <input type="search" placeholder="digite aqui sua pesquisa">
  <button data-search="next">&darr;</button>
  <button data-search="prev">&uarr;</button>
  <button data-search="clear">✖</button>
</div>

<div class="content">
  <p>Mussum Ipsum, cacilds vidis litro abertis. Paisis, filhis, espiritis santis. Quem num gosta di mé, boa gentis num é. Copo furadis é disculpa de bebadis, arcu quam euismod magna. Detraxit consequat et quo num tendi nada.</p>

<p>Viva Forevis aptent taciti sociosqu ad litora torquent. Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Aenean aliquam molestie leo, vitae iaculis nisl. Todo mundo vê os porris que eu tomo, mas ninguém vê os tombis que eu levo!</p>

<p>Cevadis im ampola pa arma uma pindureta. Não sou faixa preta cumpadi, sou preto inteiris, inteiris. Em pé sem cair, deitado sem dormir, sentado sem cochilar e fazendo pose. Interagi no mé, cursus quis, vehicula ac nisi.</p>

<p>Tá deprimidis, eu conheço uma cachacis que pode alegrar sua vidis. Mauris nec dolor in eros commodo tempor. Aenean aliquam molestie leo, vitae iaculis nisl. Quem num gosta di mim que vai caçá sua turmis! Pra lá , depois divoltis porris, paradis.</p>

<p>A ordem dos tratores não altera o pão duris. Admodum accumsan disputationi eu sit. Vide electram sadipscing et per. Manduma pindureta quium dia nois paga. Posuere libero varius. Nullam a nisl ut ante blandit hendrerit. Aenean sit amet nisi.</p>

<p>Mé faiz elementum girarzis, <a href="http://mussumipsum.com/">Site Mussum Ipsum</a> nisi eros vermeio. Nullam volutpat risus nec leo commodo, ut interdum diam laoreet. Sed non consequat odio. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis. Diuretics paradis num copo é motivis de denguis.</p>

<p>Quem manda na minha terra sou euzis! Atirei o pau no gatis, per gatis num morreus. Per aumento de cachacis, eu reclamis. Vehicula non. Ut sed ex eros. Vivamus sit amet nibh non tellus tristique interdum.</p>

<p>Si num tem leite então bota uma pinga aí cumpadi! Suco de cevadiss deixa as pessoas mais interessantis. Delegadis gente finis, bibendum egestas augue arcu ut est. Leite de capivaris, leite de mula manquis sem cabeça.</p>
</div>

  • Thanks for the reply! I liked the site of Mussum Ipsum, ksks!

1

You can use a jQuery API to color the search words at runtime, but you can tailor this code to your scenario.

It is important that all content is within one div main, and that the same is on a static page, another detail that I noticed in your code that lacks a little CSS to leave content centralized and responsive. In this link has a cool workbook so you can understand the concepts, and start thinking your next projects as mobile first.

$(function() {
  $("input").on("input.highlight", function() {
    // Determine o termo de pesquisa especificado
    var search = $(this).val();
    // Highlight termo de pesquisa dentro de um contexto específico
    $("#context").unmark().mark(search);
  }).trigger("input.highlight").focus();
});
mark {
  background: orange;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/mark.js/7.0.0/jquery.mark.min.js"></script>
<input type="text">
<div id="context">
  Mussum Ipsum, cacilds vidis litro abertis. Admodum accumsan disputationi eu sit. Vide electram sadipscing et per. Paisis, filhis, espiritis santis. Nec orci ornare consequat. Praesent lacinia ultrices consectetur. Sed non ipsum felis. Leite de capivaris, leite de mula manquis sem cabeça.
</div>

Here you get documentation from mark js..

  • Thank you very much, it’s exactly what I was looking for! Thanks for the css tip, is that I am very lay and my intention was to leave the code light, because it runs offline on a app , which was created by the service worker in an inexperienced way, and which caches the code!

  • I just implanted your code on the site, which by the way worked perfectly! But I found a new doubt: the code implanted highlights the words, but does not "find". Explaining: the words are highlighted, but as the text is large, if the word I seek is one of the last, the document does not follow it, it is always stopped at the top! How can I solve this problem? I look for something like the "Ctrl+F" of the browser, which by pressing enter the word is "found". Thanks for your help!

  • I’ve done my research and found that what I need is https://jsfiddle.net/julmot/973gdh8g/, but when I added the code on my site the browser returns me errors! Could help me by editing an example as you did earlier?

  • @Wígnyalmeida, ok I’ll check

Browser other questions tagged

You are not signed in. Login or sign up in order to post.