Reputation: 2794
I am trying to change my website background image (at body tag) when user click on a menu button and navigate to different web page.
I use jquery in _Layout.cshtml and doing like this:
<body>
<div class="page">
<header>
<br />
<div id="menubutton">
<a href="@Url.Action("Index", "Kitchen")" id="bg1">
<img src="../../Content/Layout_images/menu_kitchen.png" alt="kitchen" /></a>
<a href="@Url.Action("Index", "Stock")" id="bg2" >
<img src="../../Content/Layout_images/menu_stock.png" alt="stock" /></a>
<a href="@Url.Action("Index", "Shop")" id="bg3" >
<img src="../../Content/Layout_images/menu_shop.png" alt="shoppinglist" /></a>
</div>
<script type="text/javascript">
$(function () {
$('#menubutton a').live('click', function () {
// Get the background class from id
var bgclass = $(this).attr('id');
var temp = "url('Content/Layout_images/bg2.jpg')";
$('body').css('background-image', temp);
alert($('body').css('background-image'));
// Set the clicked menu button color
var menuclass = bgclass + "_menu";
$(this).removeClass();
$(this).addClass(menuclass);
});
});
However, although the background image change when user click on the menu button, it immediately change back to the default background image set in css (Note: eventhough I dint set any background image at css, it will immediately change back to blank background after page redirect)
Any idea why this is happening? If not mistaken, jquery .css() suppose will change the css of the particular dom? Why it will still reset after navigate to other page?
Hope can get some help here... thanks...
Upvotes: 0
Views: 652
Reputation: 636
When you click on the button, you get redirected to a new URL and the layout file is reloaded. This means you need some method for persisting the background-image information when you load the new URL.
@Url.Action("Index", "Kitchen", new { bgImage = 'image url here'} )
And then in the layout file, write a js function ( inside $(document).ready(function() {}) ) to set this bgImage parameter as background image.
Upvotes: 1