Change div background

Wratox1

Member
Reaction score
22
Hello, how can i change the backgroundimage of a div, without changing the divs size, and if the image is smaller/bigger than the div it will be centered i the div?

its for a gallery, im using miniature pictures and when you click on one a divs background changes, and this is done with javascript(onclick).

the problem i have is that if the image is to small or big, it will repeat itself or not show the whole picture, even if i have
Code:
background-repeat: no-repeat; background-position: center center ;
in my css assigned to the div..

how can i avoid this problem?
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
With background-repeat: no-repeat; your bg shouldn't repeat...

Do you have a doctype set?
Does your div have a width/height specified?
Are you sure you're changing the background-image of the div that's got the css rules you posted applied to it?
 

Wratox1

Member
Reaction score
22
With background-repeat: no-repeat; your bg shouldn't repeat...

Do you have a doctype set?
Does your div have a width/height specified?
Are you sure you're changing the background-image of the div that's got the css rules you posted applied to it?

when i press one of my miniature pictures the divs background changes, but if it is too small it repeats.
No i do not have a doctype, the divs width is 800px and height is 600px and yes im sure its the right one because when i test it changes background, but it doesnt come out as i want it :(

maybe it something to do with the way i change the background? i have the onclick event on all miniature pictures and then i call a js function and change the background like this:
Code:
document.getElementById('picture').style.background = "url(image.jpg)"

could this be the problem?
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
Changing background like that will probably override the background-repeat property... the correct syntax would be:

PHP:
document.getElementById('picture').style.backgroundImage = "url('image.jpg')"

Background is used as a shorthand, much like margin, padding, border or font...

PHP:
#someid {
    border: 1px #ff00ff solid;
    margin: 0px auto;
    padding: 0em;
    font: bold 12px Arial, Helvetica, sans-serif;
    background: #00ff00 url('myimage.jpg') no-repeat center center;
}

Edit: Oh and SET A BLOODY DOCTYPE :)
 

Wratox1

Member
Reaction score
22
Changing background like that will probably override the background-repeat property... the correct syntax would be:

PHP:
document.getElementById('picture').style.backgroundImage = "url('image.jpg')"

Background is used as a shorthand, much like margin, padding, border or font...

PHP:
#someid {
    border: 1px #ff00ff solid;
    margin: 0px auto;
    padding: 0em;
    font: bold 12px Arial, Helvetica, sans-serif;
    background: #00ff00 url('myimage.jpg') no-repeat center center;
}

Edit: Oh and SET A BLOODY DOCTYPE :)

Code:
document.getElementById('picture').style.backgroundImage = "url('image.jpg')"
did it!! thank you very much! +rep

i will set a doctype, soon.. :D

Edit:i have come up with another problem with this div and background change, this div has an original backgroundimage, but i want to be able to change the background in the gallery and that i can, but when u change to another page on my website it changes back to the original background, i want the background to be saved when you change to another page.

does anyone know how to do this?
 

UndeadDragon

Super Moderator
Reaction score
448
For that you would have to use cookies, or if you are using PHP you can use $_SESSION.
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
Add the current image in the GET parameters.
On the next page, retrieve them and set it back when the DOM is ready.

In jquery:
PHP:
$("a").click(function(){
    var address = $(this).attr('href'),
        imagelink = 'path/to/image';

   if (somecheckwithaddress(address)) {
        window.location = address+'?img='+imagelink;
    }
});

Then on the next page, retrieve the parameter 'img'.
(note that with a longer query string, you'll have to differentiate between '?' and '&')
 

Wratox1

Member
Reaction score
22
Add the current image in the GET parameters.
On the next page, retrieve them and set it back when the DOM is ready.

In jquery:
PHP:
$("a").click(function(){
    var address = $(this).attr('href'),
        imagelink = 'path/to/image';

   if (somecheckwithaddress(address)) {
        window.location = address+'?img='+imagelink;
    }
});

Then on the next page, retrieve the parameter 'img'.
(note that with a longer query string, you'll have to differentiate between '?' and '&')

how do i do this with javascript? i havent worked with jquery..
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
Get the jquery code at jquery.com, add it to your page.
Then paste this code into your page AFTER you added jQuery

PHP:
<script type="text/javascript">
(function($){
    $(function(){
        $("a").click(function(){
            var address = $(this).attr('href'),
                imagelink = 'path/to/image';

            if (somecheckwithaddress(address)) {
                window.location = address+'?img='+imagelink;
            }
        });
    });
})(window.jQuery);
</script>

Change somecheckwithaddress(address) into whatever you like:
- is the link to my domain?
- is the link to specific pages?
- ...
or just remove the if statement.

Also change the imagepath to the real path.
On the next page, retrieve the GET vars (google it: jQuery querystring)
 

Wratox1

Member
Reaction score
22
Get the jquery code at jquery.com, add it to your page.
Then paste this code into your page AFTER you added jQuery

PHP:
<script type="text/javascript">
(function($){
    $(function(){
        $("a").click(function(){
            var address = $(this).attr('href'),
                imagelink = 'path/to/image';

            if (somecheckwithaddress(address)) {
                window.location = address+'?img='+imagelink;
            }
        });
    });
})(window.jQuery);
</script>

Change somecheckwithaddress(address) into whatever you like:
- is the link to my domain?
- is the link to specific pages?
- ...
or just remove the if statement.

Also change the imagepath to the real path.
On the next page, retrieve the GET vars (google it: jQuery querystring)

that wasnt the answer of my question... i asked how could do this with javascript.. im glad youre trying to help, but i havent worked with jquery and i dont want to just jump into it, i would rather take time to learn it when i have time, and atm i dont..

so im asking again, how do i do this with javascript?
 

Lyerae

I keep popping up on this site from time to time.
Reaction score
105
jQuery is JavaScript, and it's not hard to learn.
It took me a half-hour to learn the basics.
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
First hit when I told you to google "jQuery querystring"

PHP:
function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

And like Lyerae said: jQuery IS javascript...
 

Wratox1

Member
Reaction score
22
First hit when I told you to google "jQuery querystring"

PHP:
function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

And like Lyerae said: jQuery IS javascript...

if i dont want to use jquery how could i do this?

and from what i understand(after googling some) jquery is just a library for javascript.
 

celerisk

When Zerg floweth, life is good
Reaction score
62
Two things:

1.
You do want to use jQuery. Doesn't matter how cool you are, just do it.

2.
That "getParameterByName" function is just normal javascript...
Have a look at what alert(window.location.href) will show you. Well that bunch of regular expressions is the overkill version of "how to get one part of it".
 

Wratox1

Member
Reaction score
22
Two things:

1.
You do want to use jQuery. Doesn't matter how cool you are, just do it.

2.
That "getParameterByName" function is just normal javascript...
Have a look at what alert(window.location.href) will show you. Well that bunch of regular expressions is the overkill version of "how to get one part of it".

omg im not trying to be cool or anything..

cant you just tell a way to do this without jquery?

if you cant, then tell me that:nuts:
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
omg im not trying to be cool or anything..

cant you just tell a way to do this without jquery?

if you cant, then tell me that:nuts:

What (I presume) he means is that you have to give a try to jQuery it's really, really worth a try.
 

tooltiperror

Super Moderator
Reaction score
231
Either use Fixed Locations (way too complicated to use them and be sane...) or Javascript (jQuery isn't a language, it's just a library).

jQuery is easy. It drives me crazy, but it's easy. Syntax is just ugly.
 

celerisk

When Zerg floweth, life is good
Reaction score
62
Add the current image in the GET parameters.
On the next page, retrieve them and set it back when the DOM is ready.

In jquery:
PHP:
$("a").click(function(){
    var address = $(this).attr('href'),
        imagelink = 'path/to/image';

   if (somecheckwithaddress(address)) {
        window.location = address+'?img='+imagelink;
    }
});

Then on the next page, retrieve the parameter 'img'.
(note that with a longer query string, you'll have to differentiate between '?' and '&')

Not the best of plans. Setting window.location will most likely reload the page...



For that you would have to use cookies, or if you are using PHP you can use $_SESSION.


Better plan.
Setting cookies is simple enough.

Here's a demo page that sets a cookie to whatever you enter in an input field:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cookie demo</title>
<style type="text/css">
body { background-color: white; color: black;}
</style>
<script type="text/javascript">
var cookie = function (key, value, options)
{
    var defaults = {
        'expires': 10,
        'path': '/',
        'domain': '.thehelper.net'
    };
    options = options || {};
    for (var i in defaults)
    {
        if (!options[i])
        {
            options[i] = defaults[i];
        }
    }
    if (!key)
    {
        return null;
    }
    if (arguments.length == 1 || typeof value === 'object')
    {
        var values = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie);
        return values ? decodeURIComponent(values[1]) : null;
    }
    if (value === null)
    {
        options.expires = -1;
    }
    if (typeof options.expires === 'number')
    {
        var d = new Date();
        d.setDate(d.getDate() + options.expires);
        options.expires = d;
    }
    return (document.cookie = [
        encodeURIComponent(key), '=', encodeURIComponent(String(value)),
        options.expires ? '; expires=' + options.expires.toUTCString() : '',
        options.path ? '; path=' + options.path : '',
        options.domain ? '; domain=' + options.domain : '',
        ].join(''));
};

function getCookie()
{
    var img = [B]cookie('background')[/B];
    document.getElementById('test').innerHTML = '<pre>' + (img ? 'Image: ' + img : 'no cookie set') + '</pre>';
}

function setCookie(value)
{
    [B]cookie('background', value)[/B];
    document.getElementById('test').innerHTML = '<pre>' + document.cookie + '</pre>';
    return false;
};
</script>
</head>
<body onload="getCookie()">
<form method="post" action="#" onsubmit="return setCookie(this.image.value)">
<p>
<input type="text" id="image" name="image" value="" /><input type="submit" value="Set cookie" />
</p>
</form>
<div id="test">&nbsp;</div>
</body>
</html>
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
I intend it to change loction... I'm basically hijacking every anchor tag.
But yea, cookies would work too
 
General chit-chat
Help Users

      The Helper Discord

      Staff online

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top