Change global variables by js function

Related searches

I wanna change a group of scrolling images by clicking on button. question here is how to change the global variables by these function please see the attached codes,

I wanna initiate the stack() function when onload and change the scrolling images set by onclick;

Should I add an onload event and seperately call the stack() funtions, only using the local var? thanks, Joe

var images = imagest;

function softtissue(){

    var images = imagest;
}

function bone(){

    var images = imagebone;

}
function lung(){
    var images = imagelung;
}
var stack = new ImageStack({
  images: images,
  height: '512px',
  width: '512px'
});
document.querySelector('.example').appendChild(stack);

// how to use the funciton on line 94
// for questions email felix@demont.is

var images10 = [
"https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"

];

var imagesbone = [
  "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg",
  "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
];

var imageslung = [
  "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg",
  "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg",
  "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
];

function ImageStack(options) {

  var self = this;

  self.img_array = options.images;

  self.stack = document.createElement('div');
  self.stack.style.overflow = 'auto';
  self.stack.style.maxWidth = '100%';
  self.stack.style.height = options.height;
  self.stack.style.width = options.width;
  self.stack.style.backgroundSize = 'cover'
  self.stack.style.position = 'relative';

  var typeRegex = /(\D+)/
  var sizeType = options.height.match(typeRegex)[0]

  var numberRegex = /(\d+)/
  self.height_number = Number(options.height.match(numberRegex)[0])

  self.wrapper = document.createElement('div');

  for (var i = 0; i < self.img_array.length; i++) {

    var image = document.createElement('img');
    image.src = self.img_array[i];

    image.style.display = 'none';
    image.style.position = 'absolute';
    image.style.width = options.width;
    image.style.height = options.height;
    image.style.top = 0;
    image.style.left = 0;
    image.dataset.iid = i;

    self.wrapper.appendChild(image);

  }

  self.image_elements = self.wrapper.querySelectorAll('img');

  self.scrollobject = document.createElement('div');
  self.scrollobject.style.width = '100%';
  self.scrollobject.style.position = 'absolute';
  self.scrollobject.style.zIndex = '2';
  self.img_count = (self.img_array.length > 15) ? self.img_array.length : 15;
  self.scrollobject_height = Math.floor(0.1 * self.img_count * self.height_number);

  self.scrollobject.style.height = self.scrollobject_height + sizeType;

  self.scrollUpdate = function(e) {

    self.height_number = self.stack.getBoundingClientRect().height
    self.scrollobject_height = Math.floor(0.1 * self.img_count * self.height_number);

    var sT = self.stack.scrollTop
    var hn05 = self.img_array.length - 1
    var hh = (self.scrollobject_height - self.height_number) / hn05
    scrollval = Math.floor(sT / (hh))

    self.currentimg = self.image_elements[scrollval].src

    self.stack.style.backgroundImage = 'url(' + self.currentimg + ')';

  }

  self.stack.addEventListener('scroll', self.scrollUpdate);

  self.currentimg = self.image_elements[0].src
  self.stack.style.backgroundImage = 'url(' + self.currentimg + ')';



  window.addEventListener('resize', function() {
    var stackRect = self.stack.getBoundingClientRect()

    console.log(stackRect)

    self.height_number = stackRect.height
    self.scrollobject_height = Math.floor(0.1 * self.img_array.length * self.height_number);

    self.stack.style.width = stackRect.width + 'px'
    self.stack.style.eight = stackRect.width + 'px'
  })



  self.stack.appendChild(self.wrapper);
  self.stack.appendChild(self.scrollobject);

  return self.stack;

}

/*problems here*/
/*global var*/
var images = images10;

/*local var*/
function softtissue() {
  var images = images10;
}

function bone() {

  var images = imagesbone;

}

function lung() {
  var images = imageslung;

}


/*how to switch the local var in global function*/
var stack = new ImageStack({
  images: images,
  height: '512px',
  width: '512px'
});
document.querySelector('.example').appendChild(stack);
<div>
  <button id="softtissue" type="button" onclick="softtissue();return false" class="button">
  Soft Tissue</button>
  <button id="bone" type="button" onclick="bone(); return false;" class="button">
	Bone</button>
  <button id="lung" type="button" onclick="lung(); return false" class="button">
	Lung</button>
</div>

<div class="example">
</div>

var images = imagebone; never changes the global but it initializes a local variable. It creates a local variable images inside the function. You shouldn't use var inside functions

function softtissue(){
    images = imagest;
}
function bone(){
    images = imagebone;
}
function lung(){
    images = imagelung;
}

How do I change the value of a global variable inside of a function , Javascript is a little bit different than other programming languages in the sense that you can modify global variables within functions without returning them. Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable. You can override this behaviour by declaring it locally using var, but if you don't use var, then a variable name used in a function will be global if that variable has been declared globally.

A better approach would be to use images as a parameter to a general function instead of a separate function specific to the image. That way you can add unlimited amounts of images without the need to write an extra function for each image.

So inside the change_image() function, the correct image string just gets taken from the button clicked, instead of there being a function to set some global variable.

// ImageStack mockup
function ImageStack( config ) {
  this.images = config.images;
  this.height = config.height;
  this.width = config.width;
}
ImageStack.prototype.node = function() {
  return document.createElement( 'div' ).appendChild( document.createTextNode( this.images ));
};
// click event for all the buttons
function change_image( event ) {
  var image_type = event.target.getAttribute( 'data-type' );
  var stack = new ImageStack({
    images: `image${ image_type }`,
    height: '512px',
    width: '512px'
  });
  render( stack.node() );
}
// render function.
// Could be inside the click event, but I would prefer seperate functions.
function render( image ) {
  document.querySelector('.example').appendChild( image );
}

Array.from( document.querySelectorAll( 'button' )).forEach(function( button ) {
  button.addEventListener( 'click', change_image );
});
<nav>
  <button data-type="st">ST</button>
  <button data-type="bone">BONE</button>
  <button data-type="lung">LUNG</button>
</nav>
<section class="example"></section>

Can you change a global variable's value from within a function , Global JavaScript Variables. A variable declared outside a function, becomes GLOBAL. A global variable has global scope: All scripts and functions on a web� JavaScript Global Variable. A JavaScript global variable is declared outside the function or declared with window object. It can be accessed from any function. Let’s see the simple example of global variable in JavaScript.

One approach is changing the varibility of the image

adding variability ="hidden" in the imagestack and after creating these three boxes, onclickfunction onlick choose which one to show

JavaScript Scope, Variables created outside of functions are global variables, and the code in all functions have access to all global variables. If you forget to code the var keyword in a variable declaration, the JavaScript engine assumes that the variable is global. This can cause debugging problems.

In Java, there is no global keyword, but we can use a public static variable to referring a global variable.

But, because JavaScript allows re-declaration of same variables, it can easily become a problem if a function is using a variable with same name as global variable in its scope. Normally accessing this variable's value will return the value of the current scope variable. Here is what we are talking about. Code. var age = 21; function checkAge {var age = 18; console. log (age); // Output: 18} checkAge (); Here, the function's age variable overshadows the global age variable. This is the

Your global variables (or functions) can overwrite window variables (or functions). Any function, including the window object, can overwrite your global variables and functions. The Lifetime of JavaScript Variables The lifetime of a JavaScript variable starts when it is declared.

Comments
  • I will add a demo soon
  • Why you are declaring new variable inside functions?
  • The issue is actually you are creating new variables inside the functions (by keyword var, so then the global ones are replaced-overridden by these local variables (local ones are valid in scope of function, or more exactly in scope of curly brackets- { and }
  • I think you are new to javascript, please read this documentation related to Global and local scope. oreilly.com/library/view/javascript-the-definitive/0596000480/…
  • Images could be a parameter you pass to a function that returns a new ImageStack. Then you can remove the 3 other functions and the global variable altogether.
  • Thanks a lot Shilly. actually I wanna switch stacks of different images
  • Hopefully, I can do it by adding a window.onload() at the beginning which call the image and stack function
  • Yes indeed. I didn't have the ImageStack code when I wrote this example, so it was not clear that the ImageStack includes multiple images in an array. What you can do is create one object and use imagebone, imagelung, etc as the objects keys for the arrays holding the urls. That way you still only need one variable images and you can select the correct urls as images[ image_type ] or something. In the future you could then update the code to use a config file in json or something to arrive back at the point where you do not need to edit JS code when adding images.
  • or you can use block/none as well