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.

9
  • 1
    are you included jQuery library?? Commented Jan 13, 2014 at 15:09
  • Any console.log errors? Commented Jan 13, 2014 at 15:09
  • 4
    Page will be redirected since it is a hyperlink. Commented Jan 13, 2014 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. Commented Jan 13, 2014 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. Commented Jan 13, 2014 at 15:12

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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
@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?
@PlanTheldea, The images are shown properly but, the url call is prevented so it cannot load the content it is supposed to.
@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.
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?

2 Comments

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")'); }); }
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.
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

1 Comment

you are capturing the click events for the LI elements not for the anchors.
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)');
  });
});

Comments

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;
}

2 Comments

No it will not, it will on submit, but this is not a general solution.
I want it to load the page as well. this will load the image but prevents to load the page contents because it already redirects.
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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.