kennytsz kennytsz - 14 days ago 4
Javascript Question

take out value in function (javascript)

I want to reuse recipes_number1 in '.btn-random' after I click the button, but my code is not work...
I have checked, I found that recipes_number1 can't bring out...
can anyone save me ? :(

var recipes_number1 ;


$('.btn-random').click(function(){
recipes_number1 = Math.floor(Math.random() * 3);
var photo_url = Appetizer_photos[ recipes_number1 ];
var splitText = Appetizer[ recipes_number1 ];
$('#random-photo').attr('src',photo_url);
document.getElementById("list1").innerHTML= splitText;

;
});

var Appertizer_slide = Appertizer_name[recipes_number1];

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
showDivs(slideIndex += n);
}

function showDivs(n) {
var i;
var x = document.getElementsByClassName(Appertizer_slide);
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}

Answer

I think you're asking how to get Main_Dish_slide the updated value after the click takes place:

var recipes_number1 ;
var Main_Dish_slide;

$('.btn-random').click(function(){
  recipes_number1 = Math.floor(Math.random() * 3);
  var photo_url = Appetizer_photos[ recipes_number1 ];
  var splitText = Appetizer[ recipes_number1 ];
  $('#random-photo').attr('src',photo_url);
  document.getElementById("list1").innerHTML= splitText; 
  Main_Dish_slide = Main_Dish_name[recipes_number1];
});



function showDivs(n) {
  var i;
  var x = document.getElementsByClassName(Main_Dish_slide);
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";
  }
  x[slideIndex-1].style.display = "block";
}

Same concept, you need to re-assign what Appertizer_slide is referencing - one main difference between this and the code you first provided is you will need to give Appertizer_slide a starting value if you plan on calling showDivs right away:

var recipes_number1 ;
var Appertizer_slide = Appertizer_name[Math.floor(Math.random() * 3)];

$('.btn-random').click(function(){
  recipes_number1 = Math.floor(Math.random() * 3);
  var photo_url = Appetizer_photos[ recipes_number1 ];
  var splitText = Appetizer[ recipes_number1 ];
  $('#random-photo').attr('src',photo_url);
  document.getElementById("list1").innerHTML= splitText; 
  Appertizer_slide = Appertizer_name[recipes_number1];
});



var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName(Appertizer_slide);
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";
  }
  x[slideIndex-1].style.display = "block";
}