News:

Wondering if this will always be free?  See why free is better.

Main Menu

Incorporating background switcher code

Started by samborabora, March 26, 2014, 08:14:28 PM

Previous topic - Next topic

samborabora

I've found a fairly simple background switcher code that can be seen in fully working condition here: http://jsfiddle.net/Lse3V/7/

Now, I'm trying to get this into my index.template.php, however, a few things aren't working. namely, the <body> tag is supposed to be modified to <body class="orig"> and this seems to get stripped of the child class when the page is loaded. The switcher doesn't change when it's clicked and all of the js seems broken, yet it worked perfect when I put the code into a plain .html or .php file on my server. What exactly would need to be changed to have this work in SMF? Here is the html code that needs incorporating:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body class="orig">
<a href="javascript:void(0);" id="backgroundswap"></a>


And here is the javascript:
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }

        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
             
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function(){

    window.new_bg = ["blue","red","grey","orig","green"];
    window.old_bg = ["green","blue","red","grey","orig"];

    if($.cookie('backswap')) {

        $('body').removeClass().addClass(old_bg[$.cookie('backswap')]);

    };

    //Switch backgrounds and create the cookie...

    $("#backgroundswap").click(function(){

        currentClass = $('body').attr("class");

        $('body').removeClass().addClass(new_bg[old_bg.indexOf(currentClass)]);

        $.cookie('backswap', old_bg.indexOf($('body').attr("class")), { path: '/', expires: 365 });

    });

});

//head//

(function(a){var b=a.documentElement,c=navigator.userAgent.toLowerCase().indexOf("msie")!=-1,d=false,e=[],f={},g={},h=a.createElement("script").async===true||"MozAppearance"in a.documentElement.style||window.opera;var i=window.head_conf&&head_conf.head||"head",j=window[i]=window[i]||function(){j.ready.apply(null,arguments)};var k=0,l=1,m=2,n=3;h?j.js=function(){var a=arguments,b=a[a.length-1],c=[];r(b)||(b=null),q(a,function(d,e){d!=b&&(d=p(d),c.push(d),v(d,b&&e==a.length-2?function(){s(c)&&b()}:null))});return j}:j.js=function(){var a=arguments,b=[].slice.call(a,1),c=b[0];if(!d){e.push(function(){j.js.apply(null,a)});return j}c?(q(b,function(a){r(a)||u(p(a))}),v(p(a[0]),r(c)?c:function(){j.js.apply(null,b)})):v(p(a[0]));return j},j.ready=function(a,b){r(a)&&(b=a,a="ALL");var c=g[a];if(c&&c.state==n||a=="ALL"&&s()){b();return j}var d=f[a];d?d.push(b):d=f[a]=[b];return j};function o(a){var b=a.split("/"),c=b[b.length-1],d=c.indexOf("?");return d!=-1?c.substring(0,d):c}function p(a){var b;if(typeof a=="object")for(var c in a)a[c]&&(b={name:c,url:a[c]});else b={name:o(a),url:a};var d=g[b.name];if(d)return d;for(var e in g)if(g[e].url==b.url)return g[e];g[b.name]=b;return b}function q(a,b){if(a){typeof a=="object"&&(a=[].slice.call(a));for(var c=0;c<a.length;c++)b.call(a,a[c],c)}}function r(a){return Object.prototype.toString.call(a)=="[object Function]"}function s(a){a=a||g;for(var b in a)if(a[b].state!=n)return false;return true}function t(a){a.state=k,q(a.onpreload,function(a){a.call()})}function u(a,b){a.state||(a.state=l,a.onpreload=[],w({src:a.url,type:"cache"},function(){t(a)}))}function v(a,b){if(a.state==n&&b)return b();if(a.state==m)return j.ready(a.name,b);if(a.state==l)return a.onpreload.push(function(){v(a,b)});a.state=m,w(a.url,function(){a.state=n,b&&b(),q(f[a.name],function(a){a()}),s()&&q(f.ALL,function(a){a.done||a(),a.done=true})})}function w(c,d){var e=a.createElement("script");e.type="text/"+(c.type||"javascript"),e.src=c.src||c,e.async=false,e.onreadystatechange=e.onload=function(){var a=e.readyState;!d.done&&(!a||/loaded|complete/.test(a))&&(d(),d.done=true)},b.appendChild(e)}setTimeout(function(){d=true,q(e,function(a){a()})},300),!a.readyState&&a.addEventListener&&(a.readyState="loading",a.addEventListener("DOMContentLoaded",handler=function(){a.removeEventListener("DOMContentLoaded",handler,false),a.readyState="complete"},false))})(document)


And finally, the css:
body.green{background: #3F0 url(background1.jpg) center top fixed repeat}
body.blue{background: #00F url(background2.jpg) center -80px fixed repeat}
body.red{background: #F00 url(background3.jpg) center top fixed repeat}
body.grey,html{background: #666 url(background4.jpg) repeat}
body{min-height:800px}
#backgroundswap{display:block;display:inline-block;zoom:1;width:101px;height:22px;background-image:url(http://i57.tinypic.com/21j2d94.png);background-repeat:no-repeat;margin-bottom:12px;}
body.green #backgroundswap{background-position:center bottom}
body.blue #backgroundswap{background-position:0 -66px}
body.red #backgroundswap{background-position:0 -44px}
body.grey #backgroundswap{background-position:0 -22px}
body.orig{background-position:0 0}

body.orig{
background: #FF0 url(background5.jpg) center top fixed repeat
}


This should be fairly easy, right?

Deaks

did you get this working if not dont add

<body class="orig">

just leave it as <body>

also with the css

dont add

body.orig{
background: #FF0 url(background5.jpg) center top fixed repeat
}

just overwrite the background in the already existent body tag in index.css

should work
~~~~
Former SMF Project Manager
Former SMF Customizer

"For as lang as hunner o us is in life, in nae wey
will we thole the Soothron tae owergang us. In truth it isna for glory, or wealth, or
honours that we fecht, but for freedom alane, that nae honest cheil gies up but wi life
itsel."

vkot

I have incorporated a style switcher in my forum, it changes not only the background but the whole CSS file to another CSS file. It also stores the selection in a cookie so that it will remain.

Check it out at http://forum.kithara.gr , click at the sun and moon icon at the top, and tell me if you want me to try to remember what I did and take out the code for you...
For specialized SMF installation/customization, Web Development, Linux Server Administration, click here.
Για εξειδικευμένες υπηρεσίες στα παραπάνω, πατήστε εδώ.

samborabora

Hi there, thanks so much for your help both of you, sorry about the late reply! I HAVE got it working on the root page of the forum, but it isn't currently working on ANY subpage ie: any forum posts, forums themselves, subforums, JUST the front index of the forum it is working. I didn't even have to modify anything from what I posted, belive it or not, it just seemed to start working when I picked it up again today. Any ideas why this appears to be only working on the front page?

And yes, vkot, I'd LOVE the code, it would be immensely useful for seeing what I should be doing!

vkot

#4
I hope this helps:

In index.template.php, replace:
   echo '
   <link rel="stylesheet" type="text/css" href="', $settings['theme_url'], '/css/index', $context['theme_variant'], '.css?fin20" />';

with:
   echo '
   <link rel="stylesheet" type="text/css" title="default" href="', $settings['default_theme_url'], '/css/index', $context['theme_variant'], '.css?fin20" />
   <link rel="alternate stylesheet" type="text/css" title="alternate" href="...path.to.the.dark.theme.../css/index.css?fin20">';

(replace "...path.to.the.dark.theme..." accordingly)

Add in index.template.php:
<script type="text/javascript" src="', $settings['default_theme_url'], '/scripts/styleswitcher.js?fin20"></script>
(Somewhere inside <head></head>, meaning somewhere in the section after where it says "// Here comes the JavaScript bits!")

Add somewhere in index.template.php code like this:
<a href="#" onclick="setActiveStyleSheet('default'); return false;">Change style to default</a>
<a href="#" onclick="setActiveStyleSheet('alternate'); return false;">Change style to alternate</a>


Put your index.css file in the appropriate directory (and also any image files that the CSS may call)

Put the attached styleswitcher.js in Themes/default/scripts/

Edit: This is a great styleswitcher BUT I discovered that it conflicts with PMs' auto-complete recipient and pop-up notification)
For specialized SMF installation/customization, Web Development, Linux Server Administration, click here.
Για εξειδικευμένες υπηρεσίες στα παραπάνω, πατήστε εδώ.

samborabora

Really appreciate the code, looking really good! I think your switcher is going to be way more stable than the one I'm using, not only does mine not work on any page higer than the index, but it fails on my laptop for some reason, can't work out why. Can I just ask one question? Is it possible to incorporate the five style selector that I'm using in conjunction with your switcher code? I can try and hack the two together, but I am not as experienced with js as you guys! I have been trying to hack the code I have into SMF and, as I said, it works on one of my computers on the front page, but is hit and miss on any of the posts or forum page. The switcher code I have simply sets the background position of an image with five images in one to a different position, and everything is stored into a cookie. Can this be put together with your js switcher code? I'd really, really appreciate any help with this!

vkot

You can have as many stylesheets as you want.

Add more <link rel="alternate stylesheet" ... and <a href="#" onclick="setActiveStyleSheet(' ... lines, giving each stylesheet a different name. The rest of the code remains the same.
For specialized SMF installation/customization, Web Development, Linux Server Administration, click here.
Για εξειδικευμένες υπηρεσίες στα παραπάνω, πατήστε εδώ.

samborabora

This is excellent, do I have to have the entire theme replicated in each css file? Or can I just place the background image inside the .css files and then have the switcher change only the background image?

vkot

Each CSS file of each of your themes has to define all the selectors, like the default theme's CSS file does.

Each CSS file will point to background images, in certain declarations of properties. The styleswitcher switches the CSS file only, the images are declared in the CSS. Just make sure that the pathnames of the images in the CSS are correct.

(I am not very sure of what you ask... if the above didn't help, please rephrase your question)
For specialized SMF installation/customization, Web Development, Linux Server Administration, click here.
Για εξειδικευμένες υπηρεσίες στα παραπάνω, πατήστε εδώ.

samborabora

Quote from: vkot on May 22, 2014, 04:58:23 AM
Each CSS file of each of your themes has to define all the selectors, like the default theme's CSS file does.

Each CSS file will point to background images, in certain declarations of properties. The styleswitcher switches the CSS file only, the images are declared in the CSS. Just make sure that the pathnames of the images in the CSS are correct.

(I am not very sure of what you ask... if the above didn't help, please rephrase your question)

Sorry, meant, can it be possible to, basically, have the background switcher stylesheet only contain the changes to the background and have all of the other theme information still stored in the default theme css? This way, any changes to the theme can be made in the themes css file, and the background switcher can change just that, the background, without having to define alll of the css for the theme in every background changer stylesheet?

samborabora

#10
Okay, I got my code working great with this in my header:

<head>';

echo '
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />';
echo '
<script type="text/javascript" src="/head.js"></script>';
echo '
<script type="text/javascript">head.js( "http://www.PATH-TO-FORUM.com/jquery.js","http://www.PATH-TO-FORUM.com/script.js","http://www.PATH-TO-FORUM.com/back.js",  function() { });</script>';


The contents of style.css being:

body.green{background: #3F0 url(background1.jpg) center top fixed repeat}
body.blue{background: #00F url(background2.jpg) center -80px fixed repeat}
body.red{background: #F00 url(background3.jpg) center top fixed repeat}
body.grey,html{background: #666 url(background4.jpg) repeat}
body{min-height:800px}
#backgroundswap{display:block;display:inline-block;zoom:1;width:101px;height:22px;background-image:url(backgroundswap.png);background-repeat:no-repeat;margin-bottom:12px;}
body.green #backgroundswap{background-position:center bottom}
body.blue #backgroundswap{background-position:0 -66px}
body.red #backgroundswap{background-position:0 -44px}
body.grey #backgroundswap{background-position:0 -22px}
body.orig{background-position:0 0}

body.orig{
background: #FF0 url(background5.jpg) center top fixed repeat
}


Head.js is what it is, as is jquery and script.js. Back.js contains this:

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }

        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
             
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function(){

    window.new_bg = ["blue","red","grey","orig","green"];
    window.old_bg = ["green","blue","red","grey","orig"];

    if($.cookie('backswap')) {

        $('body').removeClass().addClass(old_bg[$.cookie('backswap')]);

    };

    $("#backgroundswap").click(function(){

        currentClass = $('body').attr("class");

        $('body').removeClass().addClass(new_bg[old_bg.indexOf(currentClass)]);

        $.cookie('backswap', old_bg.indexOf($('body').attr("class")), { path: '/', expires: 365 });

    });

});


I took out <body class="orig"> and left it as <body>.

The one last thing I can't seem to figure out is how to get the background images to cache and not reload each time I change page? This is the one final hurdle, and I can put this ridiculous background switching problem to rest after three months, and hopefully it may be of use to someone.

vkot

I believe that you are making your life more complicated. And you don't need jQuery.

If you only want to change a few CSS attributes and don't want to have alternative CSS file, you can set them with javascript. http://answers.oreilly.com/topic/1819-how-to-change-an-elements-css-properties-with-javascript/
If you also want to read/store this setting in a cookie, use simple javascript too. http://www.w3schools.com/js/js_cookies.asp
For specialized SMF installation/customization, Web Development, Linux Server Administration, click here.
Για εξειδικευμένες υπηρεσίες στα παραπάνω, πατήστε εδώ.

samborabora

I agree with you, my code didn't work on my laptop, so I'm giving up with that. Your code seems rock solid, I might implement it when I have my theme finished, then I can just take three copies and alter the background code.

samborabora

Hi there Vkot, your code is great, but it loads the default theme with $settings['default_theme_url'] as opposed to my previously index.template.php which used $settings['theme_url'] for some reason, so instead of loading my forums theme, it loads the unmodified default theme. Is there a $settings[] function that can load a theme number instead?

Kindred

ummm.... guys...   WHY would you be using things like

"http://www.path-to-forum.com/back.js"

use this instead
" . $scripturl . 'back.js' ."

(and all scripts should be put in the Theme specific scripts directory, not the root forum directory!)

so, this script should be placed in Themes/YOURTHEME/scripts and you would actually be using
" . $settings['theme_url'] . '/scripts/back.js' . "

And the reason that the original used
$settings['default_theme_url']
is because  - any script not defined in a specific theme is drawn from the default theme...
so, this script should be placed in Themes/default/scripts and you would actually be using
" . $settings['default_theme_url'] . '/scripts/back.js' . "
Слaва
Украинi

Please do not PM, IM or Email me with support questions.  You will get better and faster responses in the support boards.  Thank you.

"Loki is not evil, although he is certainly not a force for good. Loki is... complicated."

samborabora

I wasn't using that URL, I just changed it for the sake of posting it here. As for $settings['default_theme_url'], that is in vkot's script and not in mine. I just need vkots script to by default NOT use the actual default theme but the theme the forum uses by default.

Quote from: Kindred on June 01, 2014, 09:55:39 AM
ummm.... guys...   WHY would you be using things like

"http://www.path-to-forum.com/back.js"

use this instead
" . $scripturl . 'back.js' ."

(and all scripts should be put in the Theme specific scripts directory, not the root forum directory!)

so, this script should be placed in Themes/YOURTHEME/scripts and you would actually be using
" . $settings['theme_url'] . '/scripts/back.js' . "

And the reason that the original used
$settings['default_theme_url']
is because  - any script not defined in a specific theme is drawn from the default theme...
so, this script should be placed in Themes/default/scripts and you would actually be using
" . $settings['default_theme_url'] . '/scripts/back.js' . "

Arantor

In which case you want $settings['theme_url'].

samborabora

Quote from: vkot on May 08, 2014, 08:19:28 AM
I hope this helps:

In index.template.php, replace:
echo '
<link rel="stylesheet" type="text/css" href="', $settings['theme_url'], '/css/index', $context['theme_variant'], '.css?fin20" />';

with:
echo '
<link rel="stylesheet" type="text/css" title="default" href="', $settings['default_theme_url'], '/css/index', $context['theme_variant'], '.css?fin20" />
<link rel="alternate stylesheet" type="text/css" title="alternate" href="...path.to.the.dark.theme.../css/index.css?fin20">';

(replace "...path.to.the.dark.theme..." accordingly)

Add in index.template.php:
<script type="text/javascript" src="', $settings['default_theme_url'], '/scripts/styleswitcher.js?fin20"></script>
(Somewhere inside <head></head>, meaning somewhere in the section after where it says "// Here comes the JavaScript bits!")

Add somewhere in index.template.php code like this:
<a href="#" onclick="setActiveStyleSheet('default'); return false;">Change style to default</a>
<a href="#" onclick="setActiveStyleSheet('alternate'); return false;">Change style to alternate</a>


Put your index.css file in the appropriate directory (and also any image files that the CSS may call)

Put the attached styleswitcher.js in Themes/default/scripts/

Changed $settings['default_theme_url'] to $settings['theme_url'] in both

Quote
echo '
   <link rel="stylesheet" type="text/css" title="default" href="', $settings['default_theme_url'], '/css/index', $context['theme_variant'], '.css?fin20" />
   <link rel="alternate stylesheet" type="text/css" title="alternate" href="...path.to.the.dark.theme.../css/index.css?fin20">';

and

Quote
<script type="text/javascript" src="', $settings['default_theme_url'], '/scripts/styleswitcher.js?fin20"></script>

And added the footer text,
Quote
<a href="#" onclick="setActiveStyleSheet('default'); return false;">Change style to default</a>
<a href="#" onclick="setActiveStyleSheet('alternate'); return false;">Change style to alternate</a>

But the links just redirect to
QuoteHTTP://WWW.FORUMURL.COM/%C3%A2%E2%82%AC%C2%9D#”
rather than changing the themes, or even attempting to?

Arantor

Well, they're going to link to # at the end which means 'don't leave the current page' and the onclick is supposed to capture the click event, but it sounds like there's something else wrong.

Kindred

looks like someone pasted from word...   look at the crap characters at the end of the URL...   suggests that the closing quotes are word's "curvy quotes" - which are not valid in code and might screw up the next code of onclick since the href was never properly closed
Слaва
Украинi

Please do not PM, IM or Email me with support questions.  You will get better and faster responses in the support boards.  Thank you.

"Loki is not evil, although he is certainly not a force for good. Loki is... complicated."

Advertisement: