0

I want a background image to change with the onclick attribute on html link tag. But its not working.

<ul>
    <li><a href="index.php?page=Home" onclick="one();">Home</a> </li>
    <li><a href="index.php?page=Achivement" onclick="two();">Achivement</a></li>

    <li><a href="index.php?page=Career" onclick="three();">Career</a></li>
    <li><a href="index.php?page=Message" onclick="four();">Message</a></li>
    <li><a href="index.php?page=opportunity">opportunity</a></li>
    <li><a href="upload1.php">Register</a>
    <li></li>
 </ul>
  <script type="text/javascript">
  function one(){

 $('body').css('background-image','url(image/back1.jpg)');

}
function two(){

   $('body').css('background-image','url(image/back2.jpg)');

}
function three(){


}
function four(){


}  </script>

as you can see I tried passing a function on the onclick attribute and I have already defined these function on the bottom already and still the background image wont change. I have checked the directory where the images are they are correct. and I havent defined any background image on my css so. I need help and its driving me crazy.

Sanjok Gurung
  • 948
  • 4
  • 17
  • 33
  • Any console.log errors? – Sergio Jan 13 '14 at 15:09
  • 1
    are you included jQuery library?? – Pranav C Balan Jan 13 '14 at 15:09
  • 4
    Page will be redirected since it is a hyperlink. – Rajaprabhu Aravindasamy Jan 13 '14 at 15:10
  • So I think the background is changing, but immediately after the change, the link actually redirects to index.php and the page is redrawn fresh. `event.preventDefault()` might be in your interest to search on. – Arthur Weborg Jan 13 '14 at 15:11
  • Pass an identifier in the url path which holds the background image index. For example index.php?page=home&background=1. Then in your js create a function to get this param and display the correct image. – Mivaweb Jan 13 '14 at 15:12
  • Also remember that partial urls in stylesheets are [relative to the source of the style sheet](http://stackoverflow.com/questions/940451/using-relative-url-in-css-file-what-location-is-it-relative-to) – Andreas Jan 13 '14 at 15:17
  • Try to inspect your page in Chrome DevTools, whether the `body` tag has `background-image` property, or not. – Oleg Jan 13 '14 at 15:18
  • @VDesign So what is the easiest way to do that, could you show me where to look?? thank you, I think your's would solve the problem. – Sanjok Gurung Jan 14 '14 at 09:48
  • @SanjokGurung I have posted an answer with code and link to used jquery library. – Mivaweb Jan 15 '14 at 08:23

6 Answers6

2

A couple things:

  1. You need to include the jQuery library (in case you did not already)
  2. You need to prevent the default action because it is a link
  3. You need to functionalize it for reuse.

Example:

<script type="text/javascript">
    $(function(){
        $('a').on('click',function(e){
            var href = this.href.split('='),
                img;

            // prevents following to the link location
            e.preventDefault();

            // determines which background image
            switch(href[1]){
                case 'Home':
                   img = 'back1.jpg';
                   break; 
                case 'Achievement':
                   img = 'back2.jpg';
                   break;
                case 'Career':
                   img = 'back3.jpg';
                   break;
                case 'Message':
                   img = 'back4.jpg';
                   break;
                case 'Opportunity':
                   img = 'back5.jpg';
                   break;
            }

            // assigns background-image
            $('body').css({backgroundImage:'url(image/'+img+')'});
        });
    });
</script>

This will allow great reuse, and eliminate the need for the inline onclick= declarations.

PlantTheIdea
  • 16,061
  • 5
  • 35
  • 40
  • I dont know how to use it as i am quite new to javascript, however will it not stop the page from calling the url index.php?page=Home etc. can I copy and paste your code, will it work?? I have included the jquery libray BTW – Sanjok Gurung Jan 14 '14 at 13:29
  • @SanjokGurung are you calling the jQuery library **before** the script shown above? and did you make sure to remove your `onclick` statements in your HTML? – PlantTheIdea Jan 14 '14 at 15:26
  • @PlanTheldea, The images are shown properly but, the url call is prevented so it cannot load the content it is supposed to. – Sanjok Gurung Jan 15 '14 at 08:22
  • @SanjokGurung - so you actually want to load the pages? are you REALLY saying you want a different background image for each PAGE? because that is quite a different request. – PlantTheIdea Jan 15 '14 at 15:16
1

You have an href along with the click. You will need to specify your link as

<li><a href="#" onclick="one();">Home</a> </li>

You will need to redirect to the page through javascript. Otherwise you are in essence asking it to go to redirect you to the URL and call your javascript but if the redirect happens how would you even see what the javascript execution yields?

Gjohn
  • 1,261
  • 1
  • 8
  • 12
  • ok I tried redirencting through javascript but im still stuck with the same problem. My href is empty and my function code is function changeImage(number) { $.post('core/changebg.php',{number:number}, function(data) { window.location="index.php?page=Message"; $('body').css('background-image','url("image/'+number+'.jpg")'); }); } – Sanjok Gurung Jan 14 '14 at 13:10
  • You are changing the window.location - perhaps add another parameter in your connection string to indicate which image and then add the code in your $(document).ready() to grab the connection string value and then change the image. – Gjohn Jan 16 '14 at 03:14
1

Remove your inline script and all your functions and try this instead:

$(function () {
    $('ul li a').on('click', function (e) {
        e.preventDefault)();
        $('body').css('background-image', 'url(image/back' + $(this).closest('li').index() + '.jpg)');
    });
});

If you just want to target the first 4 li you can add to my code a if($(this).closest('li').index() < 5){ change background };

About the links you have, if you want to use them

Sergio
  • 28,539
  • 11
  • 85
  • 132
1

Try to use this stetment for jQuery element:

$(function() {
  $('elementLink').on('click', function(e){
       e.preventDefault();
       $('body').css('background-image','url(image/back1.jpg)');
  });
});
RDK
  • 4,540
  • 2
  • 20
  • 29
0

It should be like this:

onclick="one(); return false;"

when you click a link, the new page loads, so you have to prevent this behavior by writing return false

You can also write

onclick="return one();"

and javascript:

function one(){
  $('body').css('background-image','url(image/back1.jpg)');
  return false;
}
Oleg
  • 22,300
  • 9
  • 68
  • 84
0

I would always try to keep the image src decision out of the code, and move it into the CSS file. Something like:

// could be good to keep your url params as lower case as a convention, then this
// options object could be skipped and you'd just use the param as the classname
var options = {
  'Home': 'home',
  'Achievement': 'achievement'
};

$("ul li a").click(function(e){
  e.preventDefault();

  var href = $(this).attr("href");

  if(href[1])
  {
    $("body").addClass(options[href[1]]);
  }

});

then in your css file

body.achievement
{
  background: url("/images/some_img.png");
}

body.home
{
  background: url("/images/some_img2.png");
}

That way when you want to update the srcs, or styles, you do't have to go searching through the src

p.s. I haven't run the code above, but hopefully you get the idea :)

ottis
  • 216
  • 1
  • 3