Fork me on GitHub

QueryTag.js


The simple, easy-to-implement jQuery plugin that allows you to add popular search queries from a Google Custom Search Engine (CSE) to your website as sortable, filterable, and stylable keyword tags.


Getting Started

Download and Setup


To use this plugin, include the jQuery, Isotope, and Isotope Packery-Mode libraries and the QueryTag.js plugin before the closing <body> tag of your HTML document:


Copy
<script src="jquery.js"></script>
<script src="isotope.pkgd.js"></script>
<script src="packery-mode.pkgd.js"></script>
<script src="querytag.js"></script>


Install with Bower


Copy
$ bower install querytag.js


Dependencies


Required:


Optional / Theming:

  • Bootstrap (3.1.0+)
  • QueryTag custom theme (included as querytag-theme.css)

Add-Ons:

Collapsible menu toggling using MenuAnimate, which includes 6 stylish navigation transformicons.




Usage

HTML


Required:

There are three required HTML components in order to use QueryTag.js:

  1. A <div> container with the id .#grid. This is the grid layout where the keyword tags will be displayed
  2. A <div> container with the classname .filterable with a child select element containing options for each desired view.
  3. A <div> container with the classname .sortable with child button elements for each desired sort value. Sort values are designated using the data-sort-value attribute on the button. The three built in sort values are:

    Sort by Description Data Attribute
    Name sort data by text (A to Z) data-sort-value="name"
    Popularity sort data by number (largest to smallest) data-sort-value="number"
    Category * sort data by category data-sort-value="category"
    * requires a categories.json file
Copy
// Required 1: Filterable container
<div class="filterable">
    <select>
        <option>Overall</option>
        <option>Year</option>
        <option>Month</option>
        <option>Week</option>
        <option>Day</option>
    </select>
</div>

// Required 2: Sortable container
<div class="sortable">
    <button data-sort-value="name">Name</button>
    <button data-sort-value="number">Popularity</button>
    <button data-sort-value="category">Category</button>
</div>

// Required 3: Grid of keyword tags
<div id="grid"></div>


Optional:

There are three optional HTML components to enhance the appearance and functionality of QueryTag.js:

  1. Execute a search on a keyword tag (or just copy it's value to a search input) using a <form> element with the classname .searchable. The form should have a child input with the id #search, otherwise keyword tag values will be linked to the first child input[type="search"] element.
  2. Collapsible menu using MenuAnimate toggle icons along with a <div> container with the classname .collapsible wrapped the collapsible elements.
  3. There are three conditional alert messages that can be shown or hidden based on the status and configuration of the rendered keyword tags:

    Element id Description
    #alert-results message containing the current results count for the specified filter & sort configuration
    #alert-empty message to display when there are no tag results for the specified filter/sort configuration
    #alert-error message to display for ajax-related errors

Copy
// Optional 1: Searchable form
<form class="searchable">
    // Must have id="search" or be the first child input[type="search"] element
    <label><b>Search: </b><input id="search" type="search" name="q" value=""></label>
</form>

// Optional 2: Collapsible menu
<button class="navicon"></button>
<div class="collapsible"> ... </div>

// Optional 3: Alert messages
<div id="alert-results"></div>
<div id="alert-empty"></div>
<div id="alert-error"></div>
                        




JSON


QueryTag.js requires a categories.json file in order to implement category sorting on your keyword tags. Below is the basic file structure:


Copy
{
  category1: {          // arbitrary category name (key)
    color: "label-1",   // class to assign this category for styling
    list: [             // list of keywords that comprise the category
      "methods",
      "demo",
      "properties",
      "usage"
    ]
  },

...

}

Included in the [querytag-theme.css] stylesheet are six basic category themes:

  • .label-default*
  • .label-1
  • .label-2
  • .label-3
  • .label-4
  • .label-5

* fallback style for uncategorized tags (keywords not found in any category list)




CSS


By default, QueryTag.js comes bundled with an optional theme and a succinct stylesheet to hide alerts & collapsibles.


Copy
/* initially hide alerts and collapsibles */
#alert-results, #alert-empty, #alert-error, .collapsible {
    display: none;
}};

Querytag.js was designed to blend aesthetically with the Bootstrap CSS framework and comes packaged with a default theme that looks great on both Bootstrap and non-Bootstrap websites.


Buttons

Default button style .button-default


Alerts

Tag results count #alert-results

11 results found

0 results found

Empty results message #alert-empty

Sorry, no results found for your search.

Ajax error message #alert-error

Sorry! We are unable to retrieve the search queries at this time.refresh

Sorry! We are unable to retrieve the search queries at this time.

Labels

Label category styles .label

default label 1 label 2 label 3 label 4 label 5

Navicons

Navigation menu transformicons* .navicon

*requires the MenuAnimate stylesheet




JavaScript


To use the export plugin, just call:


Copy
$("#grid").queryTag("USERID", "CSEID");

Each Google Custom Search engine is identified by a unique ID created by combining a user ID USERID with a Custom Search engine ID CSEID, separated by a colon. You can find your unique search engine ID on the Basics tab of the Custom Search control panel. It should look something like this:


Copy
//       USERID          CSEID
011737558837375720776:mbfrjmyam1g

The Google Custom Search API allows you to retrieve popular search queries for five distinct time intervals:

overall, year, month, week, day
By default, QueryTag will generate option controls for all five views. You can define which views to render by supplying a String[] of views as the optional third parameter.


Copy
/* Default: all 5 views are rendered */
$("#grid").queryTag("USER-ID", "CSE-ID", ["overall", "year", "month", "week", "day"]);
$("#grid").queryTag("USER-ID", "CSE-ID");    // same as above

/* Only the "overall" and "month" views are rendered */
$("#grid").queryTag("USER-ID", "CSE-ID", ["overall", "month"]);
                        



Methods


.queryTag( USER-ID , CSE-ID [, views ] )

Argument Type Description Required Default
1st USERID String Google CSE user ID. Yes none
2nd CSEID String Google CSE customer search engine ID. Yes none
3rd views String[] Google CSE views to render No ["overall", "year", "month", "week", "day"]


Events


Below is the list of available events:

Event Description
shown.qt Triggered after click of the toggle menu icon that results in the .collapsible container gaining visibility (display:block).
/* trigger shown.qt event on the closed toggle menu */
$(".navicon").not(".open").click();
hidden.qt Triggered after click of the toggle menu icon that results in the .collapsible container losing visibility (display:none).
/* trigger hidden.qt event on the open toggle menu */
$(".navicon").filter(".open").click();
unsort.qt Triggered after click of an (active) sort button, when tags are unsorted (restored back to their original order).
/* trigger unsort.qt event for each active sort button */
$(".sortable > button[data-sort-value]").filter(".active").click();
sort.qt Triggered after click of a (default) sort button, when tags are sorted by name, popularity, category, or any combination of the antecedent.
/* trigger sort.qt event for each inactive sort button */
$(".sortable > button[data-sort-value]").not(".active").click();
filter.qt Triggered after change of the view option, when tags are filtered based on the current view selection (i.e overall). The event object passed to the handler after a filter.qt event includes one custom property:
  • event.view returns the current view selection.
/* trigger filter.qt event on the 3rd option in the views select control */
$(".filterable select option").eq(2).attr("selected", "selected").change();
query.qt Triggered after click of a keyword tag. The event object passed to the handler after a query.qt event includes three custom properties:
  • event.tag returns the keyword tag name (text).
  • event.form returns the form element with the .searchable class.
  • event.input returns the search input element located inside the .searchable form.
/* trigger query.qt event on the 1st keyword tag */
$("#grid > .label").first().click();


Settings


Below are the default plugin settings:


Copy
/* default jQuery selectors for plugin-related elements */
$.fn.queryTag.selectors = {
        $searchForm: ".searchable",                             // (jQuery selector) search form containing search input
        $menuGroup: ".collapsible",                             // (jQuery selector) container to wrap around elements which are toggled by the ".navicon"
        $buttonGroup: ".sortable",                              // (jQuery selector) button group for sort buttons
        $selectGroup: ".filterable",                            // (jQuery selector) select control for the list of views
        $navIcon: ".navicon",                                   // (jQuery selector) menu button used to toggle ".collapsible" containers
        $alertInfo: "#alert-results",                           // (jQuery selector) alert for results count
        $alertEmpty: "#alert-empty",                            // (jQuery selector) alert for no results message
        $alertError: "#alert-error"                             // (jQuery selector) alert for ajax error
    };

/* default styles for plugin-related elements */
    $.fn.queryTag.styles = {
        category: "general",                                    // (String) default category
        button: "button-default",                               // (String) default button style
        color: "label-default",                                 // (String) default tag style
        reload: "img"                                           // (String) reload image null, "img", "fontawesome", "HTMLelement"
    };

/* relative font sizes for the popularity of keywords(queries) */
$.fn.queryTag.sizes = ["1.5em", "1.375em", "1.25em", "1.125em", "1em", "0.9375em", "0.875em"];

/* path to the JSON category file */
$.fn.queryTag.pathToJSON = "dist/data/categories.json";

/* data to be sent to the server with categories.json request */
$.fn.queryTag.data = null;

/* alert text to display when there are no results for the selected view */
$.fn.queryTag.emptyText = "Sorry, no results found for your search.";

/* alert text to display for ajax errors */
$.fn.queryTag.errorText = "Sorry! We are unable to retrieve the search queries at this time.";

/* reload button to display for ajax errors */
$.fn.queryTag.reloadStyle = {
    img: {
        src: "dist/img/refresh.png",
        element: function () {
            return "<a id='refresh' href='#'><img src=" + this.src + " alt='refresh'></a>";
        }
    },
    fontawesome: {
        size: "fa-2x",
        element: function () {
            return "<a id='refresh' title='refresh' href='#'><i class='fa fa-refresh " + this.size + "'></i></a>";
        }
    }
};


Browser Support


Chrome Firefox IE Opera Safari
Android
iOS
Mac OS X
Windows


Live Demo

Demo 1: Unstyled

Basic demo excluding the optional theme and add-on features.


Demo 2: Styled

Basic demo including the optional theme [querytag-theme.css].


Demo 3: Menu

Basic demo including the add-on toggle menu transformicons [requires the MenuAnimate stylesheet].


Demo 4: Search

Basic demo including the optional keyword tag search form.


Demo 5: Events

Interactive demo to test the six custom events triggered by QueryTag.js.




License


QueryTag.js is licensed under the terms of the MIT License
The MIT License (MIT)
Copyright (c) 2015 - Travis Clarke - https://www.travismclarke.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.



Credits


John Resig - jQuery
Metafizzy - Isotope