natanel97 natanel97 - 6 months ago 21
HTML Question

JavaScript: Check if cookie sets, and change image src to random while refreshing and cookie not expires

Excuse me for the long title. I'm trying to make something simple, function that runs on load, checks if cookie is set - if "it's true", then change the image src randomly, as below:

HTML Code:

<img id="photo" src="../photostock/3129_382a101ee6d307dfd34abad8941c35cd_8885.jpg" alt="background" />


JS Code:

function rand_photo( id ) {
var q, img, id;
var random = function(min, max) {
return Math.Floor( Math.random() * ( max - min + 1 ) ) + min;
};
q = random( 1, 3 );

var prefix = '../photostock/',
suffix = '.jpg';

switch( q ) {
case 1:
img = '3129_382a101ee6d307dfd34abad8941c35cd_8885';
break;
case 2:
img = '1404_0d03ec48b64b4b65a6820aa5a58a39af_5487';
break;
case 3:
img = '1292_5d3c0fde3f83d725eb58025a522a6097_5648';
break;
default:
img = '7395_5d3c0fde3f83d725eb58025a522a6097_4191';
}

img = prefix + img + suffix;

document.getElementById( id ).setAttribute( 'src' ) = img;
// also tried with just ".src =" - didn't worked
}

function check_create_cookie( cookie_name, ident ) {
if( document.cookie.indexOf( cookie_name ) >= 0 ) {
rand_photo( ident )
}
else {
document.cookie = cookie_name + '=1; max-age=60';
}
}

window.onload = check_create_cookie( 'sample_cookie', 'photo' );


but for some reason, it's not working...
any thoughts, notes or both?

Thank you all!

Answer

You have some typos in your code.

  1. Math.Floor does not exist: the correct form is: Math.floor
  2. document.getElementById( id ).setAttribute( 'src' ) = img; is wrong. The correct form is: document.getElementById(id).setAttribute('src', img); For details see MDN
  3. The last is: window.onload = check_create_cookie( 'sample_cookie', 'photo' ); Th correct form is well described in MDN

So, the working code is:

function rand_photo(id) {
  var q, img, id;
  var random = function(min, max) {
    return Math.floor(Math.random() * ( max - min + 1 ) ) + min;
  };
  q = random( 1, 3 );

  var prefix = '../photostock/',
      suffix = '.jpg';

  switch( q ) {
    case 1:
      img = '3129_382a101ee6d307dfd34abad8941c35cd_8885';
      break;
    case 2:
      img = '1404_0d03ec48b64b4b65a6820aa5a58a39af_5487';
      break;
    case 3:
      img = '1292_5d3c0fde3f83d725eb58025a522a6097_5648';
      break;
    default:
      img = '7395_5d3c0fde3f83d725eb58025a522a6097_4191';
  }

  img = prefix + img + suffix;

  document.getElementById(id).setAttribute('src', img);
  // also tried with just ".src =" - didn't worked
}

function check_create_cookie( cookie_name, ident ) {
  if( document.cookie.indexOf( cookie_name ) >= 0 ) {
    rand_photo( ident )
  }
  else {
    document.cookie = cookie_name + '=1; max-age=60';
  }
}

window.onload = function() {
  check_create_cookie( 'sample_cookie', 'photo' );
}
<img id="photo" src="../photostock/3129_382a101ee6d307dfd34abad8941c35cd_8885.jpg" alt="background" />