This is just a tiny little trick that might be helpful on a site where you don’t have the time or desire to build out a really good on-site search solution. Google.com itself can perform searches scoped to one particular site. The trick is getting people there using that special syntax without them even knowing it.
Make a search form:
<form action="https://google.com/search" target="_blank" type="GET">
<label>
Search CSS-Tricks on Google:
<input type="search" name="q">
</label>
<input type="submit" value="Go">
</form>
When that form is submitted, we’ll intercept it and change the value to include the special syntax:
var form = document.querySelector("form");
form.addEventListener("submit", function (e) {
e.preventDefault();
var search = form.querySelector("input[type=search]");
search.value = "site:css-tricks.com " + search.value;
form.submit();
});
That’s all.
Nice idea. But with Google, you don’t need Javascript at all. Just use a form and add
sitesearch
as hidden parameter:With Bing, where the site needs to be inside the search text box your suggestion is working and there we need JavaScript.
One note on this: if you’re using Google Analytics (or similar analytics platforms), this method might wreak havoc on your source/medium data and inflate your sessions. Basically, anyone that uses the search would get reclassified as a new session from Google, rather than how they originally got to the site.
I know this is mostly meant for dev/design, but figured I’d flag it. Cool trick to get better internal search, though!