Question

I am trying to display products in fancybox on href link onClick event. but when click event occures, it gives an error like

ReferenceError: productfancybox is not defined

I have tried this code:

HomePageProducts.cshtml:

<div class="herry-pic-cols brdr">
            <ul id="homePageFeaturedProductInit">
                @foreach (var item in Model)
                {
                    <li>
                        <span id="@item.Id">
                           @Html.Partial("_CategoryBox", item)
                           <a id="Link" href="#" onClick ="productfancybox(@item.Id);">Link</a>
                        </span>
                    </li>    
                }
            </ul>

            <div class="clear"></div>
            <a class="prev-btn2" href="#"></a>
            <a class="next-btn2" href="#"></a>
        </div>

      <script type="text/javascript">
        $(window).load(function () {

            function productfancybox(id) {

                $.fancybox({
                    'width': '80%',
                    'height': '100%',
                    'autoScale': true,
                    'transitionIn': 'fade',
                    'transitionOut': 'fade',
                    'href': '/Category/CategoryProductsFancyBox?Id='+id,
                    'type': 'iframe',
                    'onClosed': function () {
                        window.location.href = "f?p=&APP_ID.:211:&SESSION.::&DEBUG.::";
                    }
                });

            }

        });
        </script>

Why onClick event is not working?
Am i missing something?

Was it helpful?

Solution

Your function, productfancybox is scoped locally to the anonymous function called on window load. Once that occurs, it goes away and no longer exists.

Instead, you need to define your function in the global namespace (i.e. not inside a call like this), or and preferably, create a namespace and define your function there:

var MyAwesomeNamespace = MyAwesomeNamespace || {};

MyAwesomeNamespace.productfancybox = function (id) {
    ...
}

Then later, you can call:

MyAwesomeNamespace.productfancybox(1);

Anywhere in your code, after that script has run. This is just a simple example. There's better ways to set up a library for your application. Here's a basic primer you can work from: http://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top