Shopify Javascript Callbacks

From the Directed Edge Developer Base
Revision as of 06:33, 11 December 2012 by Scott (talk | contribs)
Jump to: navigation, search

Add a hover effect to the recommendations (jQuery)

This changes the text color and the border color of the image simultaneously.

{% assign directed-edge-callback = 'addHoverEffectToRecommendations' %}
{% include 'directed-edge' %}

<script type="text/javascript">
function addHoverEffectToRecommendations() {
    function findIndexInRow(e) {
        var children = e.parentElement.children;
        for(var i = 0; i < children.length; i++) { if(children[i] == e) { return i; } }
    }

    function findTitleForImage(e) {
        return $(e.parentElement).next().children()[findIndexInRow(e)];
    }

    function findImageForTitle(e) {
        return $(e.parentElement).prev().children()[findIndexInRow(e)];
    }

    $(".directededge-image-cell").hover(function() {
        $("img", this).css("border-color", "#DDD");
        $("a", findTitleForImage(this)).css("color", "#FD885D");
    }, function() {
        $("img", this).css("border-color", "#FFF");
        $("a", findTitleForImage(this)).css("color", "#242424");
    });

    $(".directededge-title-cell").hover(function() {
        $("img", findImageForTitle(this)).css("border-color", "#DDD");
        $("a", this).css("color", "#FD885D");
    }, function() {
        $("img", findImageForTitle(this)).css("border-color", "#FFF");
        $("a", this).css("color", "#242424");
    });
}
</script>

Add the items to the DOM tree without any styling

{% assign directed-edge-jsonp = 'showRecommendations' %}
{% include 'directed-edge' %}

<script type="text/javascript">
function showRecommendations(data)
{
    var container = document.getElementById("directededge-blocks");
    var products = data.related_products;

    for(var i = 0; i < products.length; i++)
    {
        var item = document.createElement("div");
        item.className = "directededge-item";
        container.appendChild(item);

        var imageLink = document.createElement("a");
        item.appendChild(imageLink);
        imageLink.className = "directededge-image-link";
        imageLink.href = products[i].link;

        var image = document.createElement("img");
        imageLink.appendChild(image);
        image.className = "directededge-image";
        image.src = products[i].image;

        var title = document.createElement("a");
        item.appendChild(title);
        title.className = "directededge-title";
        title.href = products[i].link;
        title.innerHTML = products[i].title;

        var price = document.createElement("a");
        item.appendChild(price);
        price.className = "directededge-price";
        price.href = products[i].link;
        price.innerHTML = products[i].price;
    }
}
</script>