0

Im trying to create a google redirect page on what you enter. Like you enter "xyz" on the search bar, it will search "xyz" on google. But it is not doing that. Instead it is searching "xyz" on the web. Its for a school project and I do not have much knowledge on html and css so bear with me... .

HTML Code:

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>e</title>
  <link rel="stylesheet" href="./style.css">

</head>
<body>

<div class="search-bar">
  <form class="search">
    <input type="text" id="input" name="input" placeholder="Type here..."><br>
    <button>
      <button onclick = redirect() class="fas fa-search"></button>
    </button>
  </form>
</div>


  <script>
    function redirect() {
      let input = document.querySelector('#input').value;
      location.replace("https://www.google.com/search?q=" + input) }
  </script>

</body>
</html>

CSS Code:

@import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css");

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

button {
  cursor: pointer;
  transition: 1s ease;
  font-family: inherit;
}

html {
  color-scheme: dark;
}

body {
  background-color: #202124;
  font-family: "Poppins", sans-serif;
}

.search-bar {
  max-width: 400px;
  width: 100%;
  position: absolute;
  margin-top: 180px;
  margin-left: 250px;
}

form.search {
  display: flex;
  width: min(90%, 25rem);
  border: 2px solid grey;
  border-radius: 25px;
  background-color: #202124;
  overflow: hidden;
}

form.search > * {
  padding: 0.8em 1em;
  border: none;
  background-color: transparent;
  font-size: 1.2rem;
}

form.search > :is(:focus, :focus-visible, :active){
  outline: none;
}

form.search input {
  min-width: 0;
  flex: 1;
}

form.search button i {
  transition: inherit;
}

form.search button:hover i {
  scale: 1.2;
}

Solution to make it work?

1 Answers1

0

The default type for a <button> is "submit", and clicking a submit button will submit its form. This is essentially obscuring your JavaScript code because the form submission is reloading the page.

You can change the button's type:

<button type="button" onclick="redirect()" class="fas fa-search"></button>

Other options include removing the <form> entirely, since nothing is really using it (aside from styling, which can be done with a <div> just as easily). Or keeping the markup as-is but handling (and canceling) the form's submit event instead of the button's click event.

David
  • 208,112
  • 36
  • 198
  • 279