Как сделать поиск по сайту в html
Перейти к содержимому

Как сделать поиск по сайту в html

  • автор:

How to Add a Search Bar in HTML

In this tutorial, we are going to add a search bar in HTML to your site!

I will walk you through all the components you need to add a search bar in HTML and connect it to Google to search.

Google will open in a new tab and only show results for your site.

For those in a rush, the complete solution is at the bottom of the page. For those who want the deep dive keep reading!

Let’s start with the HTML that we need to create a form.

HTML Form

The first thing we need to add is the bar itself. This uses a few HTML elements:

  • <form> — This element is for user input
  • <input> — This element has many types the one we will use today is search
  • <button> — This element will submit the form and start the search

Here is what the HTML will look like:

The above HTML is all we need to create a search bar. There are a few attributes that we are using on the <input> tag. Let’s look at these in more detail:

  • type — This sets how the input looks on the screen. There are many types such as password, checkbox and radio yet here we are using search
  • id — Setting an ID can make it easy to reference the input box from JavaScript which we will use later
  • name — It is common to use “q” for the search query box name
  • placeholder — This is some text that gives a hint to the user on what the input is for

When the HTML displays on the browser it looks like this:

For the input, we have used the type search but there is also a text type. It can be a bit confusing on which one you should pick. The two input types are almost the same except the search type has some extra functionality. For example, some browsers will add a delete button to the input tag for you:

For search boxes, it makes sense to use the search input type and that is what we are going to use here.

Our form is not quite finished yet, we need to make sure that screen readers can use it for accessibility.

To do this we have to make two changes to the form:

  1. We need to add a role to the form with the value of “search”. Setting this will cause the screen readers to announce that this form is a search form.
  2. We add a aria-label attribute to the <input> element. The screen reader will read aloud the value of this attribute. Set a value that describes what text the search form returns such as “Search through our site content”.

This is our final HTML:

Next, we are going to look at making a form pretty by styling the form with CSS.

CSS adds style to the search bar changing its look and feel.

One addition that can help the user find the search box is to add a magnifying glass or search icon. We will add one of these to the button and create a search box that looks like this:

It’s amazing what a bit of color and an icon can do! Looks much better right?

Let’s look at what we have changed to make it look like this.

First, we have added some color to the form itself:

We have set the width and height of the form. We also arrange the items in the form using the flex display.

Next, we change the look of the input search box:

The first line above resets the search box all: unset; design. Many browsers add their own design and it can be hard to style. This can make it easier to style as we need.

Then we set the font and make sure that the search bar fills the space with height and width. Lastly, we have added a bit of padding.

The next CSS rule is a bit strange! It allows us to set the style of the placeholder text inside the search box. The default is grey text, to change this we need to use this rule:

The last CSS rules change the look and feel of the button. You can see here that we have replaced the search button with a search icon.

To do this I have changed the HTML of the button to now include a svg . The svg is an image of the search icon, it now looks like this:

We can then style these two html elements like this:

We have used the all: unset; rule again to reset the button to its default. Then set a height and width of 44px this is a good size for fingers on touch screens.

Then we set the height and width of the icon and set the color to white ("#fff”).

Now our search bar is almost ready! Except nothing happens when we press the search button.

The last step for us is to hook up the button to JavaScript.

JavaScript

We are going to do a Google search when someone searches in our search bar.

To do this we need to write some code that will:

  • Add an event listener to the form so we know when someone presses the search button
  • Get the text value from the query box
  • Build a Google URL that searches a specific site
  • Opens a new tab with Google and the search query

Google allows you to search a specific site if you add site: to the query. For example, if you wanted to search PageDart for the term lazy loading you could add this in Google:

site:pagedart.com lazy loading

The great thing about this search query is that it only returns results for the site you specify. You filter Google results and no other site will appear in the results. We can use this trick to create a search results page from our search bar.

Here is the code that can do this:

The first thing we do is attach some variables to the form and search input box. Then we set the Google URL and set the site variable:

If you want to search your site then change const site = ‘pagedart.com’; to your website const site = ‘example.com’; .

We then create a function that will run each time someone presses the search button. The function will then open Google in a new tab in the browser:

The last line in the code:

Add a listener to the form. It will listen for the submit button press and run the function each time.

Now when you enter a search query and press the search icon a new tab will open up with your site and the search query.

Complete Solution

Now we have covered all the parts of a search bar:

  • HTML of the form
  • CSS to add color and design
  • JavaScript to process the form input

You can see a working codepen example.

Here is the complete HTML:

How to Add a Search Bar in HTML, Final Thoughts

You have learned in this tutorial how to add a search bar in HTML. We have covered:

  • How to create a small HTML form
  • How to design the form using CSS
  • How to write JavaScript to interact with the form

You have also learned how you can use JavaScript to connect the form to Google. Performing a search only on your site.

Using the special site search on Google you can get Google results only for your site.

Как сделать поиск по сайту в html

Создание игр на Unreal Engine 5

Создание игр на Unreal Engine 5

Данный курс научит Вас созданию игр на Unreal Engine 5. Курс состоит из 12 модулей, в которых Вы с нуля освоите этот движок и сможете создавать самые разные игры.

В курсе Вы получите всю необходимую теоретическую часть, а также увидите массу практических примеров. Дополнительно, почти к каждому уроку идут упражнения для закрепления материала.

Помимо самого курса Вас ждёт ещё 8 бесплатных ценных Бонусов: «Chaos Destruction», «Разработка 2D-игры», «Динамическая смена дня и ночи», «Создание динамической погоды», «Создание искусственного интеллекта для NPC», «Создание игры под мобильные устройства», «Создание прототипа RPG с открытым миром» и и весь курс «Создание игр на Unreal Engine 4» (актуальный и в 5-й версии), включающий в себя ещё десятки часов видеоуроков.

Подпишитесь на мой канал на YouTube, где я регулярно публикую новые видео.

Подписаться

Подписавшись по E-mail, Вы будете получать уведомления о новых статьях.

Подписаться

Добавляйтесь ко мне в друзья ВКонтакте! Отзывы о сайте и обо мне оставляйте в моей группе.

Мой аккаунт Моя группа

Какая тема Вас интересует больше?

Основы Unreal Engine 5

Основы Unreal Engine 5

Пройдя курс:

— Вы получите необходимую базу по Unreal Engine 5

— Вы познакомитесь с множеством инструментов в движке

— Вы научитесь создавать несложные игры

Общая продолжительность курса 4 часа, плюс множество упражнений и поддержка!

31 Search Form HTML For Web Design

Niemvuilaptrinh

Search component is an important component in the website. It makes it easy for users to find the content they want in your website. In today’s post, we’ll take a look at some beautiful Simple search box HTML.

Stylish search box in HTML

You can see the result below.

CSS Search Box With Icon

You can see the result below.

Stylish Search Box In HTML CSS Code

You can see the result below.

Search Box HTML CSS

You can see the result below.

Search Box HTML Code Design

You can see the result below.

Simple Search Box HTML

You can see the result below.

CSS Search Bar Styling

You can see the result below.

Responsive Search Bar

You can see the result below.

Responsive search bar CSS

You can see the result below.

Simple search box CSS

You can see the result below.

Search Form Style CSS

You can see the result below.

CSS Search Box Examples

You can see the result below.

Animated Search Bar

You can see the result below.

Search Box By Scene.js

You can see the result below.

Rounded Search Bar HTML

You can see the result below.

Search Input CSS

You can see the result below.

Input Type Search CSS

You can see the result below.

Input With Search Icon CSS

You can see the result below.

Search Icon In Input Field

You can see the result below.

Custom Search Bar HTML

You can see the result below.

Search Bar For Website HTML

You can see the result below.

Search Bar Design

You can see the result below.

Transparent search bar CSS

You can see the result below.

Bootstrap Search Box With Icon

You can see the result below.

Website Search Bar Design

You can see the result below.

Search Box With Icon Inside

You can see the result below.

Bootstrap Search Box With Icon Inside

You can see the result below.

Javascript Search Box

You can see the result below.

Animation Search Bar By GSAP

You can see the result below.

Search Bar HTML Template

You can see the result below.

Search bar template HTML CSS

You can see the result below.

Summary

I hope the article will provide you with useful Responsive search bar for web development and if you have any questions, just send an email and I will respond as soon as possible. I hope you continue to support the site so that I can write more good articles. Have a nice day!

В HTML появился новый элемент Search

В стандарте HTML появился новый семантический элемент search. Он представляет собой раздел, который используется для поиска или фильтрации данных.

Search содержит элементы управления формой (такие как поле ввода текста, выпадающее окно, кнопки и т.д.), а область поиска или фильтрации может быть любой: от одного документа до всего Интернета.

Как search работает в HTML

Перед тем, как появился элемент <search> , обычно добавляли role=»search» к тегу <form> , чтобы испрользовать форму для поиска:

Теперь достаточно использовать тег для обёртки формы:

Увы, так как <search> — это новый стандарт, понадобится время, прежде чем все браузеры и инструменты догонят его. До тех пор можно использовать хак, указывающий роль ARIA.

В будущем этот хак уже не понадобится, но сейчас он поможет подготовить код до тех пор, пока браузеры не начнут поддержку нового тега:

Это может показаться нелогичным: мы удаляем role=»search» , но все обертываем <search> . Кроме того, так выходит больше кода (аж на три символа больше), ещё и увеличивается вложенность (на один уровень больше).

Это не какая-то огромная проблема, но некоторые разработчики наверняка будут жаловаться.

Варианты использования search в HTML

Есть важный момент: <search> не обязательно должен быть текстовым вводом с кнопкой. Его можно использовать для фильтрации результатов или строк в таблицах.

Польза <search> выходит за рамки обычных текстовых вводов и поисковых полей:

В этом примере форму поиска включили в заголовок веб-страницы:

В следующем примере на странице расположены две функции поиска.

Первая находится в заголовке веб-страницы и служит глобальным поиском по сайту. На его назначение указывает title .

Вторая функция включена в <main> и позволяет искать и фильтровать данные из содержимого этой же страницы. На его назначение указывает заголовок <h2> .

Заключение

С элементом <search> все востребованные сообществом роли ARIA landmark будут закрыты. Элемент увеличивает доступность разметки (хотя и пройдет много времени, пока все браузеры подхватят идею) и расширяет семантику языка.

Однако с точки зрения программиста кажется, что элемент мало что добавляет к существующей реализации. Например, введение тэгов типа <tabpanel> и <tab> было бы гораздо ценнее.

Но это не отменяет важности <search> . Все улучшения, даже незначительные, только приветствуются. И <search> — отличное дополнение к семейству HTML.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *