Click event doesn't trigger the 'else if' statement in jQuery

Having trouble with a button click issue. In the following code, when the button is clicked, it checks if the text on the button is "day". If so, it changes the background-color of the body to red and updates the button text to "night". I am struggling with making the body background color revert and changing the button text back to "day" when the button with "night" text is clicked.

var buttonText = $('button').text();

$('button').click(function() {
  if (buttonText == 'day') {
    $('body').css({
      'background': 'red'
    })
    $('button').text('night');
  } else if (buttonText == 'night') {
    $('body').css({
      'background': 'yellow'
    })
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>

<p>velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<button type="button" name="button">day</button>

Answer №1

When it comes to programming, there are some practices that should be avoided at all costs. It is not advisable to base your logic on presentation, such as HTML values, or to directly manipulate HTML elements with CSS.

Instead, it is recommended to use classes for both your logic and presentation. This helps in maintaining a clean and organized code structure.

If you want to learn more about decoupling your HTML, CSS, and JavaScript, check out this article.

$('.js-update').click(function(e) {
  var $btn = $(e.currentTarget);  
  var addClass = $btn.data('addclass');
  var removeClass = $btn.data('removeclass');
  var target = $btn.data('target');
  $(target).addClass(addClass).removeClass(removeClass);
})
.day {
  background: red;
}
.night {
  background: yellow;
}

.day .btn-day,
.night .btn-night {
  display: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
        <link rel="stylesheet" href="training.css">
    </head>
    <body class="day">
        <p>velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </p>
        <button class="js-update btn-day"type="button" name="button" data-target="body" data-addclass="day" data-removeclass="night">day</button>
        <button class="js-update btn-night" type="button" name="button" data-target="body" data-addclass="night" data-removeclass="day">night</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
        
    </body>
</html>

Answer №2

Make sure to declare your buttonText variable inside the event handler to ensure it gets updated properly, otherwise, it will retain its initial value throughout the script.

In addition, don't forget to include setting the text back to "day" in your else block.

$('button').click(function() {
  var buttonText = $('button').text();

  if (buttonText == 'day') {
    $('body').css({
      'background': 'red'
    })
    $('button').text('night');
  } else if (buttonText == 'night') {
    $('body').css({
      'background': 'yellow'
    });
    $('button').text('day');
  }
})
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8>
  <title></title>
  <link rel="stylesheet" href="training.css">
</head>

<body>
  <p>velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
  <button type="button" name="button">day</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
  <script src="training.js" charset="utf-8"></script>
</body>

</html>

Answer №3

Transfer the text of the button into the method itself

$('button').click(function() {
    var buttonText= $('button').text();
        if (buttonText=='day') {
            $('body').css({
                'background':'red'
            })
        $('button').text('night');
    } else if (buttonText=='night') {
        $('body').css({
            'background':'yellow'
        }) 
    }
})

Answer №4

To achieve the desired functionality of changing the button text and background color, make sure to retrieve the button text within the click event handler every time a user clicks the button. This way, you can ensure that the button text is updated accordingly based on the current state.

$('button').click(function() { 
    var buttonText= $('button').text(); //get button text each time you click the button
    if (buttonText=='day') { 
        $('body').css({ 'background':'red' }) 
        $('button').text('night');
    } else if (buttonText=='night') { 
        $('body').css({ 'background':'yellow' }) 
    } 
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the secret to remaining on the same spot even after the page is reloaded?

How can I maintain the AJAX call data after a page reload? I have attempted to use code that reloads the entire page, but I would like to stay in the same location. Is there a way to achieve this without reloading the entire page? $('#updateAddressPr ...

Calculation of time intervals based on input values from text boxes, calculating quarters of an hour

I am facing a couple of challenges: -I am trying to calculate the time duration in hours between two military times input by the user in two textboxes. The result should be in quarter-hour intervals like 2.25 hours, 2.75 hours, etc. -The current calculat ...

What is the best way to utilize JavaScript variables that are declared on index.html/index.jsp in Vue.js?

Just starting out with Vue.js and I recently finished developing a Vue.js app using the terminal. I then deployed it on a Java web application and noticed that everything works fine when running it as is. However, I now need to pass a csrftoken to my Vu ...

Google Chart Fails to Display

I am encountering an issue while attempting to integrate a Google chart into my project. The page fails to load, rendering a blank screen. Initially, the page displays correctly for a brief moment after loading and then suddenly turns blank, becoming unres ...

When attempting to use the $http get command, an error may occur due

Is there a way to capture these errors in an Ionic application? ionic.bundle.js:25000 GET net::ERR_CONNECTION_REFUSED Using the following code snippet: $http.get('http://' + ip + '/?custom=1&cmd=' + cmd); I have attempted var ...

Is it possible for an animation to complete even if it is stopped midway?

I am currently working on a media player project where I have implemented a scrolling marquee effect for the song meta information using JavaScript and CSS. The scrolling effect only occurs when the track is playing, and I achieve this by adding/removing ...

Angular UI Bootstrap Typeahead - Apply a class when the element is added to the document body

In my current project, I am utilizing angular bootstrap typeahead with multiple instances. Some of these instances are directly appended to the body using the "typeahead-append-to-body" option. Now, I have a specific instance where I need to customize the ...

"Implementing conditional evaluation for pixel units in AngularJS using ng-style

Looking to adjust the style of an element based on its height. For example, if the height is less than X, apply 'style 1'; otherwise, apply 'style 2'. The syntax appears to be correct, but accurately evaluating the height property in p ...

Struggling with setting up a search bar for infinite scrolling content

After dedicating a significant amount of time to solving the puzzle of integrating infinite scroll with a search bar in Angular, I encountered an issue. I am currently using Angular 9 and ngx-infinite-scroll for achieving infinity scrolling functionality. ...

Using jQuery to Create and Export XLS File

Need assistance with exporting data to an xls file sorted by date. Unsure how to resolve this issue. Here is the jQuery Code : $('#report_xls').live("click", function(){ var url = "ticket.report.php"; var startdate = $('input:text[ ...

Restrict certain sections of the website to authorized users only

In my game project, players are presented with two options: to play the game itself or to view global and local highscores. I have implemented a signup and login system where upon successful login, users can choose among playing the game, checking highscor ...

What could be causing the format to be incorrect?

docker run -it -v "%cd%":/e2e -w /e2e cypress/included:6.2.1 --browser chrome When attempting to execute this command within Visual Studio Code, an error is encountered: docker: invalid reference format. See 'docker run --help' Vario ...

Interactive feature on Google Maps information window allowing navigation to page's functions

Working on an Angular2 / Ionic 2 mobile App, I am utilizing the google maps JS API to display markers on a map. Upon clicking a marker, an information window pops up containing text and a button that triggers a function when clicked. If this function simpl ...

Use flexbox to manage the width of containers and control the wrapping of elements

Hello, I am a newcomer to utilizing flexbox in CSS. I have these "boxes" that need to maintain their width and wrap when the screen size is small. On a large screen: https://i.sstatic.net/dXnGC.png On a small screen: https://i.sstatic.net/8rZso.pn ...

Utilizing React Classes Based on Conditions

I'm attempting to add the class active if commentBadgeActive is true. The Scholar image should transition from grayscale to colored. <Paper className={classes.paper}> <div className={classes.profile}> < ...

The mysterious anomaly in Vue.js

I am attempting to assign a data object named types upon receiving a response in the ready() method. This is what I have: export default { data () { return { types: null } }, ready () { TypeService.showAll(1) .then(functio ...

Sort arrays in Javascript by their respective lengths

Is there a way to arrange these arrays in descending order of the number of items they contain? I believe the logic is correct, but I might be missing some essential methods. The current output is empty. //Declare Variables var TN = ['Chattanooga&apo ...

Visualizing data with a grouped bar chart in D3.js

I am currently working on creating a vertical bar chart using D3.js, similar to the one shown in this (source: statcan.gc.ca) However, I am facing an issue as I am unable to display two sets of data for comparison. Following a tutorial from , I have cr ...

What is the best way to update the amount input using Ajax?

I am looking to transfer the price selected from a drop-down list into an input field. I have the jQuery code in place to capture the selected value from the drop-down, but I understand that Ajax is needed for the next step. However, I'm unsure of how ...

What is the best way to access the "placeholder" configuration of a jQuery UI sortable?

Instead of returning a string as expected, the documented way seems to be: $('#sortable').sortable('option', 'placeholder'); However, this actually returns an object instead of the placeholder value I used in the configurati ...