Set index parameter for Algolia instant search product - javascript

Currently I am working with Algolia autocomplete search template - please see documentation here and Magento 2.
I want to add index number to each product appeared dynamically when using search input field. It can be added as a dataset attribute. Please see below code and place marked as data-index="INDEX_NUMBER_HERE".
Attribute 'index' should be equal to the search position number. So if in my search results I have 6 products then the first product should has data-index="1", the second one data-index="2" and so on until the last one with data-index="6"
I know that I can add extra JavaScript code here but maybe someone knows how to do that based on some {{AlgoliaIndexVariable}} same as I can fetch in my example {{objectID}}, {{url}}, etc.?
This is my current template:
<script type="text/template" id="autocomplete_products_template">
<a class="algoliasearch-autocomplete-hit" id="productAlgoliaSearch_{{objectID}}" href="{{url}}">
{{#thumbnail_url}}
<div class="thumb">img here</div>
{{/thumbnail_url}}
<div class="info">
product info here
</div>
<div class="data" data-index="INDEX_NUMBER_HERE"></div>
</a>
</script>
many thanks for useful tips

The template does expose variable called __hitIndex but it's zero based. You can't increment it directly from the template. You can increment it in JavaScript though. You can use the __hitIndex for the data-index and increment it at the time you retrieve it.

Related

How to check if a array input field starts with specific string in jquery [duplicate]

Just wondered how I would search for all the ids starting with "content_" in the whole page and also a way to only find them in a named div called "extra_content". Once i have all the ids i want to hide them.
Below is an example of what i want to find.
<div id="content_1"></div> <-- Find
<div id="content_2"></div> <-- Find
<div id="contet_3"></div>
<div id="extra_content">
<div id="content_extra_1"></div> <-- Find
<div id="content_extra_2"></div> < -- Find
</div>
Examples would be helpful.
Thanks
Use the attribute-starts-with selector:
$('[id^="content_"]').hide();
To limit the search to elements within extra_content:
$('#extra_content [id^="content_"]').hide();

Javascript code for alphabetizing divs

I'm editing a web page that has a list of doctors names and images wrapped in a div. I'm adding more to that list and my client wants all of the names in alphabetical order now. As apposed to manually doing that (I know my client will also be adding more doctors in the future)I tried writing a script to do the work for me. I wrapped each doctor in a div called "alphabetize," and set a span id of "lastName" around each doctor's last name.
<div class="alphabetize large-6 columns sameheight-wrap">
<div class="large-4 medium-4 columns sameheight PadT20"> <img src="../imgs/dev/crna-staff/John-Doe.jpg" alt=" John Doe, CRNA" class="pictureBottomBorder"> </div>
<div class="large-8 medium-8 columns contenttable sameheight PadT20">
<div class="border vmid text-center bgdblue PadB"> <span class="white medium"><strong>John<span id="lastName">Doe</span></strong><br>
</span> <span class="white PadT5"> MSN, Thomas Jefferson University School of Nurse Anesthesia</span> </div>
</div>
</div>
I placed the following script on that page;
<script>
var $divs = $("div.alphabetize");
$(function() {
var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
return $(a).find("#lastName").text() > $(b).find("#lastName").text();
});
$("#alpha").html(alphabeticallyOrderedDivs);
});
</script>
For some reason, the script is not working correctly. Doctors are out of order and i also need to add a variable to the code that sorts the last names with the first 3 letters. Can anyone help? Javascript is not my strong suit. Not sure if I missed something.
Below is a snippet that will show you how you can easily sort this. The major issue, however, is the following:
return $(a).find("#lastName").text() > $(b).find("#lastName").text();
The sort() function asks to return one of three values, 0 to maintain position, -1 to move it before the current element and 1 to move it after. That means that all you could ever return is after and not before, so your sort fails.
For the solution I would like to suggest using a data-attribute and no more HTML spans and styles that need to be rendered (and probably hidden afterwards), so here is my suggestion:
<div data-alphabetize="John Doe">John Does Content</div>
We can string together a couple of functions to get the correct output. We will need prototype.slice.call to convert the returned-by-querySelector NodeList to an Array, then we need to use sort to sort it alphabetically and finally we can use forEach to go through the array and insert the nodes in the correct position.
I am using vanilla JS - mostly to show how simple things can be done without loading up jQuery. You can, of course, do this with jQuery as well.
// Turn querySelectorAll NodeList into an Array
Array.prototype.slice.call(document.querySelectorAll('[data-alphabetize]'))
// Sort the array by data-alphabetize attribute (reverse order)
.sort(function(a, b){
return a.getAttribute('data-alphabetize') < b.getAttribute('data-alphabetize')
? 1 : -1;
})
// Insert every node in order
.forEach(function(v, i, a){
var parent = v.parentNode;
parent.removeChild(v);
parent.insertBefore(v, parent.childNodes[0]);
});
<div>
<div data-alphabetize="Beta">Joseph Alfred <strong>Beta</strong></div>
<div data-alphabetize="Alpha">Mark Unicode <strong>Alpha</strong></div>
<div data-alphabetize="Gamma">Graham <strong>Gamma</strong>-Python</div>
<div data-alphabetize="Omega">Matthew <strong>Omega</strong></div>
</div>

How can I structure my MustacheJS template to add dynamic classes based on the values from a JSON file?

OBJECTIVE
To build an app that allows the user to search for locations.
CURRENT STATE
At the moment the locations listed are few, so they are just all presented when landing on the "dealers" page.
BACKGROUND
Previously there were only about 50 showrooms carrying a product we sell, so a static HTML page was fine.
And displays as
But the page size grew to about 1500 lines of code after doing this. We have gotten more and need a scalable solution so that we can add many more dealers fast. In other projects, I have previously used MustacheJS and to load in values from a JSON file. I know the ideally this will be an AJAX application. Perhaps I might be better off with database here?
Below is what I have in mind so far, and it "works" up to a certain point, but seems not to be anywhere near the most sustainable solution that can be efficiently scaled.
HTML
<a id="{{state}}"></a>
<div>
<h4>{{dealer}} : {{city}}, {{state}} {{l_type}}</h4>
<div class="{{icon_class}}">
<ul>
<li><i class="icon-map-marker"></i></li>
<li><i class="icon-phone"></i></li>
<li><i class="icon-print"></i></li>
</ul>
</div>
<div class="listingInfo">
<p>{{street}} <br>{{suite}}<br>
{{city}}, {{state}} {{zip}}<br>
Phone: {{phone}}<br>
{{toll_free}}<br>
{{fax}}
</p>
</div>
</div>
<hr>
JSON
{ "dealers" : [
{
"dealer":"Benco Dental",
"City":"Denver",
"state":"CO",
"zip":"80112",
"l_type":"Showroom",
"icon_class":"listingIcons_3la",
"phone":"(303) 790-1421",
"toll_free":null,
"fax":"(303) 790-1421"
},
{
"dealer":"Burkhardt Dental Supply",
"City":"Portland",
"state":"OR",
"zip":"97220",
"l_type":"Showroom",
"icon_class":"listingIcons",
"phone":" (503) 252-9777",
"toll_free":"(800) 367-3030",
"fax":"(866) 408-3488"
}
]}
CHALLENGES
The CSS class wrapping the ul will vary based on how many fields there are. In this case there are 3, so the class is "listingIcons_3la"
The "toll free" number section should only show up if in fact, there is a toll free number.
the fax number should only show up if there is a value for a fax number.
For conditionals, you can use
{{#toll_free}}
{{toll_free}}
{{/toll_free}}
Which will only display the content in between the tags if it is not null, undefined, or false. Otherwise, it will completely ignore that content.
For the listing icons class, you should simplify your html to use the li for both the icon and the text. That way you can surround the whole thing in conditionals from Mustache and avoid having to deal with using such classes entirely. An example would be:
{{#toll_free}}
<li><i class="icon-phone"></i>{{toll_free}}</li>
{{/toll_free}}
Using CSS, you can achieve the same look you have now with some padding. I made a fiddle to show this and the working template code, based roughly on your example: http://jsfiddle.net/NGwge/
You may want to check out mustache conditionals (with a poc) at http://www.elated.com/res/File/articles/development/easy-html-templates-with-mustache/sections-conditional.html. That will take care of 2 and 3
With the ".length" piece from Mustache Conditions and Loops, you should be able to accomplish 1
The CSS class wrapping the ul will vary based on how many fields
there are. In this case there are 3, so the class is
"listingIcons_3la"
The "toll free" number section should only show up if in fact, there
is a toll free number.
the fax number should only show up if there is a value for a fax
number.

jQuery Masonry remove function example

I have implemented jQuery masonry to our site and it works great. Our site is dynamic and users must be able to add/remove masonry box's. The site has an add example but no remove example. Our db is queried returning x number of items. Looping through they are loaded and displayed. Here's a code sample: (we are use F3 framework and the F3:repeat is it's looping mechanism.).
<div id="container" class="transitions-enabled clearfix" style="clear:both;">
<F3:repeat group="{{#productItems}}" value="{{#item}}">
<div id="{{#item.itemId}}">
<div class="box">
<div class="view"> <!-- for css -->
<a onclick='quickRemove("{{#item.itemId}}")>
<img src="{{#item.pic}}" />
</a>
</div>
<p>
{{#item.title}}
</p>
</div>
</div>
</F3:repeat>
</div>
In the javascript code the item id number is unique and is passed into the function. It's also the div id# to distinguish each box. I've tried various combinations and methods but can't seem to get this to work.
function quickRemove(item){
var obj = $('#'+item+'').html(); // item is the product id# but also the div id#
$('#container').masonry('remove',obj);
$('#container').masonry('reloadItems');
$('#container').masonry('reload');
}
Has anyone out there successfully removed an item and how did you do it?
Thx.
Currently you appear to be passing a string full of html to the masonry remove method. Pass it the actual jQuery wrapped element by not including .html()
function quickRemove(item){
var obj = $('#'+item+''); // item is the product id# but also the div id#
$('#container').masonry('remove',obj);
$('#container').masonry('reloadItems');
$('#container').masonry('reload');
}

Switching between <div> elements using buttons

I have a specific goal in mind.
Please reference this page: http://cubancomplex.kodingen.com/test/MM/dashboard1.html
On the very bottom right, there is a <div> with two buttons on each side. The <div> currently has one google chart contained inside.
The goal is for a user to be able to use those two buttons to switch between charts for approximately eight cities.
I am not familiar with javascript or jQuery so I would appreciate any assistance! How should I go about achieving this?
Here is the code for that section:
<div id="footer">
<div class="markerNavLeft" title="Prev" id="prevMarker">‹</div>
<div id="markers">
<div id="chart">
<div id="auckland_chart_div"></div>
</div>
</div>
<div class="markerNavRight" title="Next" id="nextMarker">›</div>
</div>
Based on my experience, there's 2 option that you can use..
you can place your charts in your div id="chart". The first one add a class to mark it as a selected one (e.g. selected), of course the other is hidden… Please add a same class for all of the chart(e.g. chart-detail). Then, you can use
var temp = $(".selected").next(".chart-detail"); $(".selected").removeClass("selected"); temp.addClass("selected");
for the previous button, you can use .previous function.
You can use ajax ( .ajax function or .load function). Mark each chart with an ID so, you know what's the next or previous chart (within php).

Categories

Resources