I'm working with a friend who is using the free Google Custom Search on his site. He has a widget which searches through a list of network-member blogs (on various platforms) and then returns the results. I'm wondering if there's a way to add a button - using jQuery or JavaScript - which will perform a search with a random term.
This SO article seems plausible through creating a second action button which adds a random term from an array of popular tags or topics, but it seems like there should be something more straightforward.
The point being that people can go to the search engine, click on "Random Post" have have some articles returned for inspiration, etc. From what I can tell, the Google Search API (now deprecated) could have done that fairly easily. I can't seem to find anyone trying to do something similar using a custom search and I'd appreciate a little direction. Thanks.
The solution is included in the Custom Search API :
Use the execute()
method of the element object returned by google.search.cse.element.getElement()
var queries = ['custom search', 'random', 'google', 'Brian Bennett'];
document.querySelector('button').addEventListener('click', function() {
var cseElement = google.search.cse.element.getElement('standard0');
var rand = Math.floor( Math.random() * queries.length);
cseElement.execute( queries[rand] );
}, false );
<script>
(function() {
var cx = '011833858776650720395:4l5dii3zv2w';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:search></gcse:search>
<button>Random search</button>