Search code examples
javascriptjqueryshort

how do i write this shorter jquery?


i want shorter this code but idk how

    var theme;

    theme = 'summer' // for set default in source code

        if (  theme == 'summer' ) {
            $('.paper').css({'background-image':'url("summer.jpg")'});
            }
        if ( theme == 'spring' ) {
            $('.paper').css({'background-image':'url("spring.jpg")'});
        }

    // and set theme when user select ..

    $('#select ul li').click(function(){

        theme = $(this).attr('class');

        if (  theme == 'summer' ) {
            $('.paper').css({'background-image':'url("summer.jpg")'});
        }
        if ( theme == 'spring' ) {
            $('.paper').css({'background-image':'url("spring.jpg")'});
        }

    });

this code working but i want something like this

    var theme;
    theme = 'summer'
    $('#select ul li').click(function(){
       theme = $(this).attr('class');
    });

    if (  theme == 'summer' ) {
        $('.paper').css({'background-image':'url("summer.jpg")'});
        }
    if ( theme == 'spring' ) {
        $('.paper').css({'background-image':'url("spring.jpg")'});
    }

the theme varibale was changing when user select something but doesn't change paper background-image .. :(


Solution

  • Without making fundamental changes to your code, you can move the part that makes the change to its own function then call that function on startup and on click:

    function setTheme(theme) {
        if (theme == 'summer') {
            $('.paper').css({'background-image':'url("summer.jpg")'});
        }
        if (theme == 'spring') {
            $('.paper').css({'background-image':'url("spring.jpg")'});
        }
    }
    
    $(function() { 
        // change on click
        $('#select ul li').click(function(){
            theme = $(this).attr('class');
            setTheme(theme);
        });
    
        // and on startup
        setTheme('summer');
    });
    

    There are, of course, plenty of other ways to improve your code and to reduce the code content.

    One recommendation would be to use CSS to change the background-image and then add/remove classes; but I believe the intention of the question is more to do with DRY using the code in the question as an example rather than the final code to be reduced.