mockingjay
mockingjay

Reputation: 308

use a variable's value before change it - JavaScript

How can I use a variable's value before I change it in the same line. I want some thing like this:

document.getElementById("id").style.display = this == "none"? "initial" : "none";

something in the place of "this" to refer to that variable's value, without repeating the name/path or whatever it's called.

Thanks in advance.

Upvotes: 0

Views: 85

Answers (3)

jl_
jl_

Reputation: 5539

Not sure about the requirement in place, but here is a sample snippet to help you with:

window.onload = function() {

  setInterval(function() { // To have some effect on display

    document.getElementById("myDiv").style.display =

      (function() {
        var display = document.getElementById("myDiv").style.display;
        return display;
      })() // Self invoke

    == "none" ? "block" : "none"; // Manage

  }, 1000);

}
#myDiv {
  display: none;
  border: 1px solid red;
  padding: 20px;
}
<div id="myDiv" class="myDivClass" style="display: none">Hello!</div>


Using Arrow functions:

setInterval(function() { // To have some effect on display
  var element = document.getElementById("myDiv");

  element.style.display =

    (() => {
      return element.style.display;
    })() // Self invoke

  == "none" ? "block" : "none"; // Manage

}, 1000);
#myDiv {
  display: none;
  border: 1px solid red;
  padding: 20px;
}
<div id="myDiv" class="myDivClass" style="display: none">Hello!</div>

Upvotes: 0

trincot
trincot

Reputation: 350077

You could use an Immediately Invoked Function Expression so you assign variables on the fly. With ES6 arrow syntax, that looks like this:

((t,k) => t[k] = t[k] == "none"? "initial" : "none")
                           (document.getElementById("id").style, 'display');
A word is <span id="id">not</span> hidden 

Upvotes: 0

SimpleJ
SimpleJ

Reputation: 14768

Use variables:

var el = document.getElementById("id");
var display = el.style.display;

el.style.display = display == "none" ? "initial" : "none";

Upvotes: 1

Related Questions