Bryan
Bryan

Reputation: 91

JQuery .css() function with conditional logic

I'm practicing conditional logic within certain JQuery functions. $('h2').css({backgroundColor: 'red'}); works, but when I add the conditional logic below it no longer works. If I change the return value to a string it will get rid of the error, but it still doesn't change the background color. What am I doing wrong?

$('h2').css({function(){
    if (1 === 1){
        return backgroundColor: 'red';
    }
    else {
        return backgroundColor: 'purple';
    }
}});

Upvotes: 3

Views: 6723

Answers (4)

Alberto I.N.J.
Alberto I.N.J.

Reputation: 1853

Try this code:

$('h2').css({backgroundColor: (1 === 1) ? 'red' : 'purple'});

It's the shorthand of if condition.

In this case, the shorthand of if condition is more reliable and cleaner.

By the way, it's a plain old javascript.

Hope it helps.

Upvotes: 10

MrAlex6204
MrAlex6204

Reputation: 167

Is more cleaner keep your style in the style sheet file and is more cleaner to use the toggleClass handler

.highlight{//Put this in your style sheet file
    background-color : red;
}

'//===>This will add the to the element the highlight if it doesn't have it or else will returned back to the original style

$('h2').on('click',function(){
    $(this)toggleClass('highlight');
})

Upvotes: -3

Joseph Marikle
Joseph Marikle

Reputation: 78520

Fascinating thought experiment! The issue is that you are passing a function reference to the .css function which accepts strings and objects only. Try encapsulating the function so it returns the return result rather than the function reference:

$('h2').css((function(){
  if (1 === 1){
    return {backgroundColor: 'red'};
  }
  else {
    return {backgroundColor: 'purple'};
  }
})());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Cool thought experiment</h2>

Upvotes: 5

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60527

Your example code will cause a syntax error. You can use callback functions for jQuery.css in one of two ways.

An object with properties and their callback functions.

$('h2').css({
    backgroundColor: function(){
        if (1 === 1){
            return 'red';
        }
        else {
            return 'purple';
        }
    }
});

Or with a single property and callback function pair.

$('h2').css('backgroundColor', function(){
    if (1 === 1){
        return 'red';
    }
    else {
        return 'purple';
    }
});

In this way, you can conditionally apply CSS per-element.

Upvotes: 11

Related Questions