Home > OS >  AJAX response, boolean value creating a different CSS custom
AJAX response, boolean value creating a different CSS custom

Time:01-27

My webpage is receiving through AJAX GET requests Arrays with strings, and a Boolean.

The objects within the array are displayed subsequently to shape a chat app, the received array represents messages to display in a chatbox. However, some of the messages are bot's answers, stored as a user message.

Therefore, to recognize such message, I added a Boolean Value (bot=True : This is a bot answer). Such message has to be displayed on the right of the chatbox, when user messages are diplayed on the left. My code is brute forcing the left side of the chatbox, whatever the boolean value. HTML:

<div id="display" ></div>

CSS:

.chat {
  border-top: 1px solid #CCC;
  margin-top: 1em;
  border-radius: 2px;
  color: white;
  padding-top: 1em;
  padding-bottom: 1em;
  display: flex;
  flex-direction: column;
}

JS:

<script>
$(document).ready(function() {
  function imgMarkup(model) {
    if (model.mediasrc) {
      return `<img class='imgchat' src=../static/${model.mediasrc}.png/>`
    }
    return '';
  }
  setInterval(function() {
    $.ajax({
      type: 'GET',
      url: "/checkview",
      success: function go(response) {
        console.log(response);
        $("#display").empty();
        for (var model of response.models_to_return) {
          const temp = `
    <div class='chat'>
      <span class='time-left'>${model.datetime}</span>
      <b>${model.user_id}</b>
      <p>${model.room}</p>
      ${imgMarkup(model)}
    </div>`;
          $("#display").append(temp);
        }
      },
      error: function(response) {
        //alert('An error occured')
      }
    });
  }, 1000);
})
</script>

I would like to be able to add a second class to my .chat (css), like depending on the boolean value of the variable 'bot' from the AJAX response.

CodePudding user response:

Use a variable to hold the additional class, and set it conditionally based on model.bot.

$(document).ready(function() {
  function imgMarkup(model) {
    if (model.mediasrc) {
      return `<img class='imgchat' src=../static/${model.mediasrc}.png/>`
    }
    return '';
  }
  setInterval(function() {
    $.ajax({
      type: 'GET',
      url: "/checkview",
      success: function go(response) {
        console.log(response);
        $("#display").empty();
        for (var model of response.models_to_return) {
          let botclass = model.bot ? 'right' : '';
          const temp = `
    <div class='chat ${botclass}'>
      <span class='time-left'>${model.datetime}</span>
      <b>${model.user_id}</b>
      <p>${model.room}</p>
      ${imgMarkup(model)}
    </div>`;
          $("#display").append(temp);
        }
      },
      error: function(response) {
        //alert('An error occured')
      }
    });
  }, 1000);
})

CodePudding user response:

`<div >
// ...
`

This syntax is condition:

condition ? true : false
  • Related