Problem with dropdown blog filters

Hi everyone,

I’ve the same problem as here but it’s not work on my side.

I’ve tried something like this

{% set my_topics = blog_tags('default', 250) %}
<select id="blog-categories">
 <option value="https://pages.onestock-retail.com/en/blog/" selected>Tout afficher</option> <!-- Filter by topic -->
 {% for item in my_topics %}
 <option value="{{ blog_tag_url(group.id, item.slug) }}">{{ item }}</option>
{% endfor %}
</select> 

<script>
$(function(){
 $('#blog-categories').on('change', function () {
 var url = $(this).val();
 if (url) { 
 window.location = url;
 }
 return false;
 });
});
</script>

but as you can see here it’s not efficient for me. Maybe have I doing something wrong or miss something.

Many thanks by advance for your help!

Hi @SebastienR,

What do you want to achieve, because the filter does work over here.

The only think you could add it to add a active state of go back to the archive page when being on a tag page.

Then you could use this:

{% set my_topics = blog_tags('default', 250) %}
<select id="blog-categories">

 {# Show listing page option on tag page #}
 {% if topic %}<option value="{{ group.absolute_url }}">Tout afficher</option>{% endif %}

 {# Filter by topic #}
 {% for item in blog_topics %}
 <option {% if item == blog_topic.slug %}selected{% endif %} value="{{ blog_tag_url(group.id, item.slug) }}">
 {{ blog_topic }}
 </option>
 {% endfor %}
</select>

In some cases changes on the HubSpot blog can have caching difficulties. When you have changed your code, try removing the caching with the HubSpot developer extention addon for chrome or add this (?hsCacheBuster=5973) after your url and change the number to change the cache version.

Hi @SebastienR ,
Please search (Blog tag filter) name and then clone the module and use where you want it will fetch your topic automatically:Screenshot by Lightshot

Hope this helps!

If we were able to answer your query, kindly help the community by marking it as a solution.
Thanks and Regards.

Many thanks to both of you for your answer.

I have added the blog-tag-filter :slightly_smiling_face:

@Indra , following @webdew 's instruction, I have added “blog-tag-filter” to my page.

Now I have this Blog | OneStock

Thanks to this (html) :

{% set my_tags = blog_tags('default', 250) %}
{% set currentURL = content.absolute_url|regex_replace('^(http|https):', '') %}

<div class="blog-tag-filter">
 <select class="blog-tag-filter__drop-down">
 <option {% if currentURL == group.absolute_url|regex_replace('^(http|https):', '') %}selected="selected"{% endif %} value="{{ group.absolute_url }}">{{ module.default_filter_text }}</option>
 {% for item in my_tags %}
 <option {% if currentURL == blog_tag_url(group.id, item.slug) %}selected="selected"{% endif %} value="{{ blog_tag_url(group.id, item.slug)|regex_replace('^(http|https):', '') }}">{{ item }}</option>
 {% endfor %}
 </select>
</div>

and this (js) :

(function() {
 // Variables
 var blogTagSelect = document.querySelector('.blog-tag-filter__drop-down');

 // Functions
 blogTagSelect.addEventListener('change', function() {
 if (blogTagSelect.value) {
 window.location = blogTagSelect.value;
 }
 return false;
 });
})();

Now here are my new questions :

1/ How can I hide the 1st line of my dropdown content as you can see here

More like a label as an option.

2/ When I click on a category, I’m redirected to the category’s page. BUT, I have not this category written on the input, it’s style the 1st option (for the moment, the one I would make desappeared)

3/ How can I modify css to make the dropdown content looks like the one below (Search)

Many thanks by advance.

@SebastienR

1. I think this part will remove you first option. So try disable it with {# your hubl #}

<option {% if currentURL == group.absolute_url|regex_replace('^(http|https):', '') %}selected="selected"{% endif %} value="{{ group.absolute_url }}">{{ module.default_filter_text }}</option>

2. The my_tags<.code> will loop through all you categories. With currentURL it will automatically set an selected="selected" attribute as it’s selected.

3. @webdew referred to the ‘Blog tag filter’ module. If you clone this module you can add your own style to is inside the module. You can also apply your styling inside your theme.

Many thanks for your answers @Indra!

Sorry for the late answer, I just came back from holidays.

As you can see, I’ve well advance on this case : Blog | OneStock

Here are some more questions:

A/ Do you know why with search_input module, when I insert a word, the results appeared without the word I search ?
For example, I enter “Ship”, then it’s appear some results as “From Store : les 10 bonnes pratiques” instead of “Ship From Store : les 10 bonnes pratiques”.

B/ I have a blog per language with fr/blog, en/blog, etc.
Can I have results in search input onlu in the language I’m? Here the results are in all languages…

Here is the JS code for A/ and B/

var hsSearch = function(_instance) {
 var TYPEAHEAD_LIMIT = 100;
 var KEYS = {
 TAB: 'Tab',
 ESC: 'Esc', // IE11 & Edge 16 value for Escape
 ESCAPE: 'Escape',
 UP: 'Up', // IE11 & Edge 16 value for Arrow Up
 ARROW_UP: 'ArrowUp',
 DOWN: 'Down', // IE11 & Edge 16 value for Arrow Down
 ARROW_DOWN: 'ArrowDown',
 };
 var searchTerm = '',
 searchForm = _instance,
 searchField = _instance.querySelector('.hs-search-field__input'),
 searchResults = _instance.querySelector('.hs-search-field__suggestions'),
 searchOptions = function() {
 var formParams = [];
 var form = _instance.querySelector('form');
 for (
 var i = 0;
 i < form.querySelectorAll('input[type=hidden]').length;
 i++
 ) {
 var e = form.querySelectorAll('input[type=hidden]')[i];
 if (e.name !== 'limit') {
 formParams.push(
 encodeURIComponent(e.name) + '=' + encodeURIComponent(e.value)
 );
 }
 }
 var queryString = formParams.join('&');
 return queryString;
 };

 var debounce = function(func, wait, immediate) {
 var timeout;
 return function() {
 var context = this,
 args = arguments;
 var later = function() {
 timeout = null;
 if (!immediate) {
 func.apply(context, args);
 }
 };
 var callNow = immediate && !timeout;
 clearTimeout(timeout);
 timeout = setTimeout(later, wait || 200);
 if (callNow) {
 func.apply(context, args);
 }
 };
 },
 emptySearchResults = function() {
 searchResults.innerHTML = '';
 searchField.focus();
 searchForm.classList.remove('hs-search-field--open');
 },
 fillSearchResults = function(response) {
 var items = [];
 items.push(
 "<li id='results-for'>Results for \"" + response.searchTerm + '"</li>'
 );
 response.results.forEach(function(val, index) {
 items.push(
 "<li id='result" +
 index +
 "'><a href='" +
 val.url +
 "'>" +
 val.title +
 '</a></li>'
 );
 });

 emptySearchResults();
 searchResults.innerHTML = items.join('');
 searchForm.classList.add('hs-search-field--open');
 },
 getSearchResults = function() {
 var request = new XMLHttpRequest();
 var requestUrl =
 '/_hcms/search?&term=' +
 encodeURIComponent(searchTerm) +
 '&limit=' +
 encodeURIComponent(TYPEAHEAD_LIMIT) +
 '&autocomplete=true&analytics=true&' +
 searchOptions();

 request.open('GET', requestUrl, true);
 request.onload = function() {
 if (request.status >= 200 && request.status < 400) {
 var data = JSON.parse(request.responseText);
 if (data.total > 0) {
 fillSearchResults(data);
 trapFocus();
 } else {
 emptySearchResults();
 }
 } else {
 console.error('Server reached, error retrieving results.');
 }
 };
 request.onerror = function() {
 console.error('Could not reach the server.');
 };
 request.send();
 },
 trapFocus = function() {
 var tabbable = [];
 tabbable.push(searchField);
 var tabbables = searchResults.getElementsByTagName('A');
 for (var i = 0; i < tabbables.length; i++) {
 tabbable.push(tabbables[i]);
 }
 var firstTabbable = tabbable[0],
 lastTabbable = tabbable[tabbable.length - 1];
 var tabResult = function(e) {
 if (e.target == lastTabbable && !e.shiftKey) {
 e.preventDefault();
 firstTabbable.focus();
 } else if (e.target == firstTabbable && e.shiftKey) {
 e.preventDefault();
 lastTabbable.focus();
 }
 },
 nextResult = function(e) {
 e.preventDefault();
 if (e.target == lastTabbable) {
 firstTabbable.focus();
 } else {
 tabbable.forEach(function(el) {
 if (el == e.target) {
 tabbable[tabbable.indexOf(el) + 1].focus();
 }
 });
 }
 },
 lastResult = function(e) {
 e.preventDefault();
 if (e.target == firstTabbable) {
 lastTabbable.focus();
 } else {
 tabbable.forEach(function(el) {
 if (el == e.target) {
 tabbable[tabbable.indexOf(el) - 1].focus();
 }
 });
 }
 };
 searchForm.addEventListener('keydown', function(e) {
 switch (e.key) {
 case KEYS.TAB:
 tabResult(e);
 break;
 case KEYS.ESC:
 case KEYS.ESCAPE:
 emptySearchResults();
 break;
 case KEYS.UP:
 case KEYS.ARROW_UP:
 lastResult(e);
 break;
 case KEYS.DOWN:
 case KEYS.ARROW_DOWN:
 nextResult(e);
 break;
 }
 });
 },
 isSearchTermPresent = debounce(function() {
 searchTerm = searchField.value;
 if (searchTerm.length > 2) {
 getSearchResults();
 } else if (searchTerm.length == 0) {
 emptySearchResults();
 }
 }, 250),
 init = (function() {
 searchField.addEventListener('input', function(e) {
 if (searchTerm != searchField.value) {
 isSearchTermPresent();
 }
 });
 })();
};

if (
 document.attachEvent
 ? document.readyState === 'complete'
 : document.readyState !== 'loading'
) {
 var searchResults = document.querySelectorAll('.hs-search-field');
 Array.prototype.forEach.call(searchResults, function(el) {
 var hsSearchModule = hsSearch(el);
 });
} else {
 document.addEventListener('DOMContentLoaded', function() {
 var searchResults = document.querySelectorAll('.hs-search-field');
 Array.prototype.forEach.call(searchResults, function(el) {
 var hsSearchModule = hsSearch(el);
 });
 });
}

var input = document.getElementsByClassName('hs-search-field__input')[0];
input.addEventListener('keydown', function(e) {
 if (e.key == 'Enter') {
 e.preventDefault();
 }
});

C/ Have you a tips to update css to change this dropdown please? And make it looks like the dropdown I have created for search input.

Many thanks!

Sebastien

Hi @SebastienR,

A. search_input results

When using the search_input, it will seach onto that page and will display the title of the page or blog as title. But if your search query is containing a word that is later onto the page, it will also show up.

If you want to dive more into the way it works, you could check out the article ‘Content Search’ and look at ‘How is the search precedence determined?’

B/ I have a blog per language with fr/blog, en/blog, etc.

For a multilingual seach you will need to customize the module.

I recommend checking out the related question: Multilingual search function

So after the input field types you will need to add the input field with language tag.

To make it more dynamical you can use the following code:

<input type="hidden" name="language" value="{{ html_lang }}">

Hope this answered your questions.