mjmitche
mjmitche

Reputation: 2067

Variables in jQuery

I have two questions about this:

  1. I am trying to assign an image to a variable img1 and then insert that variable img1 into the CSS, but it's not working. What am I doing wrong in the code below? (Note, the code works fine if I don't use a variable i.e. if I put the image path directly into it, so I know there must be a problem with the variable)

  2. Assuming that I can get the img1 variable to work, can I somehow turn it into an id or class so that I can manipulate it with jQuery? For example, I would like to be able to do $("img1").hide(1000) in the same way I do it with the class .contactform in the code below.

    var img1 = url('/wp-content/themes/custom/images/blah.jpg') repeat;
    
    $("#submit").click(function(){
        $(".contactform").hide(1000,function(){
            $(".contactforms").css({display:"block"});
            $("body.custom").css({background: "img1"});
    
        });
    });
    

Upvotes: 0

Views: 103

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 477040

Try saying:

var img1 = "url('/wp-content/themes/custom/images/blah.jpg') repeat;";

With the quotes. Your JS engine should have complained. Always check the error console!

For Part 2, you could write a little helper:

function setImage(img) {
  $("#submit").click(function() {
    $(".contactform").hide(1000,function() {
        $(".contactforms").css({display:"block"});
        $("body.custom").css({background: img});
    });
  });
}

Originally you'd say setImage(img1), but you can later call it again with different parameters. If you only need to change the filename, perhaps something like this:

function setImageFilename(filename) {
  setImage("url('/wp-content/themes/custom/images/" + filename + "') repeat;");
}

Upvotes: 0

shelhamer
shelhamer

Reputation: 31130

$("body.custom").css({background: "img1"}); should be $("body.custom").css({background: img1});

"img1" is a literal string for the characters "img1" whereas img1 is a variable identifier.

Upvotes: 1

Christopher Armstrong
Christopher Armstrong

Reputation: 7953

That's not valid Javascript syntax. You need to wrap your img1 in quotes so it's recognized as a string. Try this:

var img1 = "url('/wp-content/themes/custom/images/blah.jpg') repeat";

$("#submit").click(function(){
    $(".contactform").hide(1000,function(){
        $(".contactforms").css({display:"block"});
        $("body.custom").css({background: img1});

    });
  });

Upvotes: 2

Related Questions