Dev
Dev

Reputation: 153

Set JQuery propeties to Image folder path in img src tag

Question background:

I'm trying to set two propeties of a JQuery function to an img src who's images are stored in the Images folder of my MVC site.

The Issue:

The following code shows the properties nextText and prevText being set to a left and right .jpg I have in the Images folder of my site:

    $(document).ready(function () {
    $('.bxslider').bxSlider({
        nextSelector: '#slider-next',
        prevSelector: '#slider-prev',
        controls: true,
        pager: false,
        nextText: '<img src="~/Images/rightArrow.jpg" height="25" width="25"/>',
        prevText: '<img src="~/Images/leftArrow.jpg" height="25" width="25"/>'
    });

Currently the above produces a broken Image on my page. Can I use the ~ to get the relative path on an img src tag? If I supply an external image url from Google in the img src then that works.

How can i correctly set the nextText and prevText properties so they use an Image in the Images folder on my site?

Upvotes: 0

Views: 2179

Answers (1)

Ankush Jain
Ankush Jain

Reputation: 6999

Just create a baseUrl in script tag in your layout page.

<script type="text/javascript">
 var baseUrl = "@Url.Content("~")";
</script>

and use that in your script like below:

 $(document).ready(function () {
    $('.bxslider').bxSlider({
        nextSelector: '#slider-next',
        prevSelector: '#slider-prev',
        controls: true,
        pager: false,
        nextText: '<img src="'+baseUrl +'Images/rightArrow.jpg" height="25" width="25"/>',
        prevText: '<img src="'+baseUrl +'Images/leftArrow.jpg" height="25" width="25"/>'
    });

This will work even after deployment. I had same problem and I use this way to solve this problem.

Upvotes: 2

Related Questions