wtp
wtp

Reputation: 249

adding a class to body in jquery fails in javascript methods

below is my scenario

I have three classes box with randomly selected image and from array items, there is a square box002 at right lower portion, this can be drag and droppped to any of three box if it find match the box will dissappear. likwise three box will dissappear.

then a class bodyblue is added to body with backgroundImage named middle bg is added to body for 10 seconds . after again 3 box appear for drag and drop.

in the second level after this three boxes are dragged&dropped and deleted, when bodyblue is added to body the backgroundImage middle bg is not appearing in for 10 seconds.

How to add bodyblue backgroundImage to body using jquery in second level and third level?

var array2 = [];
var arraycart = [];
var disparray = [];
var bg = [];
var dataURL;
var timeOut;
counter = 0;

var items = [{
 label: '1',url: 'https://via.placeholder.com/150x150.jpg?text=image1'},
  {label: '2',url:'https://via.placeholder.com/150x150.jpg?text=image2'},
  {label: '3',url:'https://via.placeholder.com/150x150.jpg?text=image3'},
  {label: '4',url:'https://via.placeholder.com/150x150.jpg?text=image4'},
  {label: '5',url:'https://via.placeholder.com/150x150.jpg?text=image5'},
  {label: '6',url:'https://via.placeholder.com/150x150.jpg?text=image6'},
  {label: '7',url:'https://via.placeholder.com/150x150.jpg?text=image7'},
  {label: '8',url:'https://via.placeholder.com/150x150.jpg?text=image8'},
  {label: '9',url:'https://via.placeholder.com/150x150.jpg?text=image9'},
  {label:'10',url:'https://via.placeholder.com/150x150.jpg?text=image10'}
];


var notes = ['https://via.placeholder.com/150x150.jpg?text=image1',
  'https://via.placeholder.com/150x150.jpg?text=image2',
  'https://via.placeholder.com/150x150.jpg?text=image3',
  'https://via.placeholder.com/150x150.jpg?text=image4',
  'https://via.placeholder.com/150x150.jpg?text=image5',
  'https://via.placeholder.com/150x150.jpg?text=image6',
  'https://via.placeholder.com/150x150.jpg?text=image7',
  'https://via.placeholder.com/150x150.jpg?text=image8',
  'https://via.placeholder.com/150x150.jpg?text=image9',
  'https://via.placeholder.com/150x150.jpg?text=image10'
];


var tempimages = [];
var notesselected = [];

array2 = items.slice();

var item;


//change backgroundImage


function changemainbackground() {

  bodycontents = document.getElementById('main');

  if (counter >= 0) {
    bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
    d = bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
  }
  counter++;
}
hiddenimgnumber = 0;

var images = ['https://picsum.photos/200/300', 'https://picsum.photos/200/300', 'https://picsum.photos/200/300'];

//var bg=['https://via.placeholder.com/150x150.jpg?text=image1','https://via.placeholder.com/150x150.jpg?text=image2'];
var bg = ['https://picsum.photos/200/300?image=2', 'https://picsum.photos/200/300?image=3', 'https://picsum.photos/200/300?image=4'];

var refreshIntervalId = setInterval(function() {
  image = document.getElementById('hiddenimageid');
  image.src = images[hiddenimgnumber];
}, 1)


function hiddenimage() {

  clearInterval(refreshIntervalId);
  image = document.getElementById('hiddenimageid');
  image.src = images[hiddenimgnumber];

  //console.log(hiddenimgnumber);
  hiddenimgnumber++;
}
window.onload = function() {}

function rvalue() {
  elements = document.getElementsByClassName("box");

  for (var i = 0; i < elements.length; i++) {
    //debugger;
    elements[i].style.border = "2px solid  #c57232 ";
    elements[i].style.borderBottom = "5px solid  #c57232 ";
    //object.style.borderRadius = "1-4 length|% / 1-4 length|%|initial|inherit"

  }

  ptags = document.querySelectorAll('[name="values"]');
  boxtags = document.getElementsByClassName("box");
  if (array2.length === 0) {
    alert('Game completed');
    return;

  }

  for (var index = 0; index < 3; index++) {
    randomIndex = Math.floor(Math.random() * array2.length)

    item = array2[randomIndex];
    array2.splice(randomIndex, 1);

    try {
      //ptags[index].style.visibility = "visible";
      //ptags[index].textContent = "RS."+item.label;
      ptags[index].dataset.itemLabel = item.label;

      //using label as an identity
      tempimages.push({
        data: item,
        label: item.label
      });
      notesselected.push({
        data: item.url,
        label: item.label
      });

      boxtags[index].style.backgroundImage = 'url(' + item.url + ')';

    } catch (err) {
      // console.log('Exception');
    }
  }

  var tlen = tempimages.length;
}


function displayAllImages() {
  try {

    if (tempimages.length == 0) {
      rvalue();

    }

    if (tempimages.length === 0) {
      image = document.getElementById('slide');
      image.style.display = 'none';
      return;
    }

    var arr2 = tempimages;
    item = arr2[Math.floor(Math.random() * arr2.length)]

    image = document.getElementById('slide');
    //getting notes item
    //console.log(item);
    ///////console.log(item.label);
    var dataURL = notes.filter(a => a.indexOf("?text=" + item.label) > 0)[0];
    //var dataURL =item.url;
    //var dataURL = item.label;
    console.log(dataURL);
    image.src = dataURL;
    image.dataset.itemLabel = item.label;

  } catch (err) {
  }
};

$(function() {
  displayAllImages();
});

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev) {

  ev.preventDefault();
  var data = ev.dataTransfer.getData("Text");


  var x = document.getElementById("slide").dataset.itemLabel;
  var y = ev.target.dataset.itemLabel;

  if (ev.target.tagName === "DIV") {
    y = ev.target.children[0].dataset.itemLabel;
  }
  if (x == y) {
    ev.currentTarget.style.backgroundColor = 'initial';
    ev.currentTarget.style.backgroundImage = 'initial';
    ev.currentTarget.style.border = 'initial';
    var pParagraph = ev.currentTarget.firstElementChild;

    pParagraph.style.visibility = "hidden";

    item = this.item;
    tempimages = tempimages.filter(a => a.label !== item.label);



    if (tempimages.length == 0) {
      rvalue();
      hiddenimage();
      animateCongrat();

    }
    displayAllImages();
  } else {

  }
}

//animate congarat starts here

var timeOut;
function animateCongrat() {
  $('.congrats').show();

  clearTimeout(timeOut);
  addBlueBody();
  hideCongratAndBlueBody();
}
function addBlueBody() {

  $("html").css("background-color", "  #070755  ");
  $('body').addClass('bodyblue')
  $('#container').hide();
  $('#2container').hide();
  $('#3container').hide();
  $('#2').hide();
  $('.completed').hide();
}

function hideCongratAndBlueBody() {
  timeOut = setTimeout(() => {
    $('.congrats').hide();
    $("html").css("background-color", "");
    $('body').removeClass('bodyblue')
    $('#container').show();
    $('#2container').show();
    $('#3container').show();
    $('#2').show();
    $('.completed').hide();
    changemainbackground();
  }, 10000);

}
body {
  overflow: hidden;
}

.dashed {
  border: 2px dashed #999 !important;
}

.bodyblue {
  background-image: url(https://via.placeholder.com/1000x600?text=Middle+bg);
  height: 100vh;
  width: 100vw;
}

ul {
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
}

.box {
  width: calc(33.3% - 4px);
  border-radius: 5px;
  border: #000 border-color: #e6e600;
  margin: -2px;
  background-color: #99ffff;
  height: 16vh;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-repeat: no-repeat;
  background-size: cover;
  cursor: pointer;
}

.box002 {
  position: absolute;
  top: 40.3vh;
  left: 50.98vw;
  cursor: pointer;
    border: 2px solid black;
}

.box002 img {
  width: 15.0vw;
  height: 15.0vh;
  border-radius: 0%;
}

#container {
  white-space: nowrap;
  border: px solid #CC0000;
}

.containerr {
  border: px solid #FF3399;
}

.pic {
  background-size: 100% 100%;
}

.container2 {
  width: 29.0vw;
  position: fixed;
  top: 23.9vh;
  left: 19.2vw;
}

body {
  background-image: url(https://picsum.photos/200/300?image=0);
  background-size: 100vw 100vh;
}

.reset img:hover {
  opacity: 1
}

.hiddenimage {
  position: absolute;
  top: 4.3vh;
  left: 50vw;
  cursor: pointer;
}

.hiddenimage img {
  width: 10.3vw;
  height: 10.5vh;
  border-radius: 15%;
}

.hand {
  position: absolute;
  top: 45.3vh;
  left: 17vw;
  cursor: pointer;
}

.hand img {
  width: 25.3vw;
  height: 25.5vh;
  border-radius: 0%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="main">
<div class="container2">
  <div class="containerr">
    <div class="pic" id="content">


      <div id="container">

        <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10" style="">
          <p name="values"></p>
        </div>
        <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
          <p name="values"></p>
        </div>
        <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
          <p name="values"></p>
        </div>
      </div>

    </div>
  </div>
</div>

<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
  <img src="" draggable="true" id="slide" border="rounded" />
</div>

<div class="congrats">
  <div class="hiddenimage" style="display:none;">
    <img src="" id="hiddenimageid" />
  </div>
</div>
</body>

Upvotes: 0

Views: 78

Answers (1)

Mihai T
Mihai T

Reputation: 17687

The problem is not that you are not applying bodyblue class to body. bodyblue class is applied 2nd time also. But after 1st time, you set a background-image to body via javascript. Which is a more 'powerfull' style than with css. It has a higher priority so it overrides the styles from css in the 2nd attempt.

So you could use a more specific selector body#main.bodyblue in CSS or even !important.

See below

var array2 = [];
var arraycart = [];
var disparray = [];
var bg = [];
var dataURL;
var timeOut;
counter = 0;

var items = [{
 label: '1',url: 'https://via.placeholder.com/150x150.jpg?text=image1'},
  {label: '2',url:'https://via.placeholder.com/150x150.jpg?text=image2'},
  {label: '3',url:'https://via.placeholder.com/150x150.jpg?text=image3'},
  {label: '4',url:'https://via.placeholder.com/150x150.jpg?text=image4'},
  {label: '5',url:'https://via.placeholder.com/150x150.jpg?text=image5'},
  {label: '6',url:'https://via.placeholder.com/150x150.jpg?text=image6'},
  {label: '7',url:'https://via.placeholder.com/150x150.jpg?text=image7'},
  {label: '8',url:'https://via.placeholder.com/150x150.jpg?text=image8'},
  {label: '9',url:'https://via.placeholder.com/150x150.jpg?text=image9'},
  {label:'10',url:'https://via.placeholder.com/150x150.jpg?text=image10'}
];


var notes = ['https://via.placeholder.com/150x150.jpg?text=image1',
  'https://via.placeholder.com/150x150.jpg?text=image2',
  'https://via.placeholder.com/150x150.jpg?text=image3',
  'https://via.placeholder.com/150x150.jpg?text=image4',
  'https://via.placeholder.com/150x150.jpg?text=image5',
  'https://via.placeholder.com/150x150.jpg?text=image6',
  'https://via.placeholder.com/150x150.jpg?text=image7',
  'https://via.placeholder.com/150x150.jpg?text=image8',
  'https://via.placeholder.com/150x150.jpg?text=image9',
  'https://via.placeholder.com/150x150.jpg?text=image10'
];


var tempimages = [];
var notesselected = [];

array2 = items.slice();

var item;


//change backgroundImage


function changemainbackground() {

  bodycontents = document.getElementById('main');

  if (counter >= 0) {
    bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
    d = bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
  }
  counter++;
}
hiddenimgnumber = 0;

var images = ['https://picsum.photos/200/300', 'https://picsum.photos/200/300', 'https://picsum.photos/200/300'];

//var bg=['https://via.placeholder.com/150x150.jpg?text=image1','https://via.placeholder.com/150x150.jpg?text=image2'];
var bg = ['https://picsum.photos/200/300?image=2', 'https://picsum.photos/200/300?image=3', 'https://picsum.photos/200/300?image=4'];

var refreshIntervalId = setInterval(function() {
  image = document.getElementById('hiddenimageid');
  image.src = images[hiddenimgnumber];
}, 1)


function hiddenimage() {

  clearInterval(refreshIntervalId);
  image = document.getElementById('hiddenimageid');
  image.src = images[hiddenimgnumber];

  //console.log(hiddenimgnumber);
  hiddenimgnumber++;
}
window.onload = function() {}

function rvalue() {
  elements = document.getElementsByClassName("box");

  for (var i = 0; i < elements.length; i++) {
    //debugger;
    elements[i].style.border = "2px solid  #c57232 ";
    elements[i].style.borderBottom = "5px solid  #c57232 ";
    //object.style.borderRadius = "1-4 length|% / 1-4 length|%|initial|inherit"

  }

  ptags = document.querySelectorAll('[name="values"]');
  boxtags = document.getElementsByClassName("box");
  if (array2.length === 0) {
    alert('Game completed');
    return;

  }

  for (var index = 0; index < 3; index++) {
    randomIndex = Math.floor(Math.random() * array2.length)

    item = array2[randomIndex];
    array2.splice(randomIndex, 1);

    try {
      //ptags[index].style.visibility = "visible";
      //ptags[index].textContent = "RS."+item.label;
      ptags[index].dataset.itemLabel = item.label;

      //using label as an identity
      tempimages.push({
        data: item,
        label: item.label
      });
      notesselected.push({
        data: item.url,
        label: item.label
      });

      boxtags[index].style.backgroundImage = 'url(' + item.url + ')';

    } catch (err) {
      // console.log('Exception');
    }
  }

  var tlen = tempimages.length;
}


function displayAllImages() {
  try {

    if (tempimages.length == 0) {
      rvalue();

    }

    if (tempimages.length === 0) {
      image = document.getElementById('slide');
      image.style.display = 'none';
      return;
    }

    var arr2 = tempimages;
    item = arr2[Math.floor(Math.random() * arr2.length)]

    image = document.getElementById('slide');
    //getting notes item
    //console.log(item);
    ///////console.log(item.label);
    var dataURL = notes.filter(a => a.indexOf("?text=" + item.label) > 0)[0];
    //var dataURL =item.url;
    //var dataURL = item.label;
    //console.log(dataURL);
    image.src = dataURL;
    image.dataset.itemLabel = item.label;

  } catch (err) {
  }
};

$(function() {
  displayAllImages();
});

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev) {

  ev.preventDefault();
  var data = ev.dataTransfer.getData("Text");


  var x = document.getElementById("slide").dataset.itemLabel;
  var y = ev.target.dataset.itemLabel;

  if (ev.target.tagName === "DIV") {
    y = ev.target.children[0].dataset.itemLabel;
  }
  if (x == y) {
    ev.currentTarget.style.backgroundColor = 'initial';
    ev.currentTarget.style.backgroundImage = 'initial';
    ev.currentTarget.style.border = 'initial';
    var pParagraph = ev.currentTarget.firstElementChild;

    pParagraph.style.visibility = "hidden";

    item = this.item;
    tempimages = tempimages.filter(a => a.label !== item.label);



    if (tempimages.length == 0) {
      rvalue();
      hiddenimage();
      animateCongrat();

    }
    displayAllImages();
  } else {

  }
}

//animate congarat starts here

var timeOut;
function animateCongrat() {
  $('.congrats').show();

  clearTimeout(timeOut);
  addBlueBody();
  hideCongratAndBlueBody();
}
function addBlueBody() {

  $("html").css("background-color", "  #070755  ");
  $('body').addClass('bodyblue')
  $('#container').hide();
  $('#2container').hide();
  $('#3container').hide();
  $('#2').hide();
  $('.completed').hide();
}

function hideCongratAndBlueBody() {
  timeOut = setTimeout(() => {
    $('.congrats').hide();
    $("html").css("background-color", "");
    $('body').removeClass('bodyblue')
    $('#container').show();
    $('#2container').show();
    $('#3container').show();
    $('#2').show();
    $('.completed').hide();
    changemainbackground();
  }, 10000);

}
body {
  overflow: hidden;
}

.dashed {
  border: 2px dashed #999 !important;
}

body#main.bodyblue {
  background-image: url(https://via.placeholder.com/1000x600?text=Middle+bg)!important;
  height: 100vh;
  width: 100vw;
}

ul {
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
}

.box {
  width: calc(33.3% - 4px);
  border-radius: 5px;
  border: #000 border-color: #e6e600;
  margin: -2px;
  background-color: #99ffff;
  height: 16vh;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-repeat: no-repeat;
  background-size: cover;
  cursor: pointer;
}

.box002 {
  position: absolute;
  top: 40.3vh;
  left: 50.98vw;
  cursor: pointer;
    border: 2px solid black;
}

.box002 img {
  width: 15.0vw;
  height: 15.0vh;
  border-radius: 0%;
}

#container {
  white-space: nowrap;
  border: px solid #CC0000;
}

.containerr {
  border: px solid #FF3399;
}

.pic {
  background-size: 100% 100%;
}

.container2 {
  width: 29.0vw;
  position: fixed;
  top: 23.9vh;
  left: 19.2vw;
}

body {
  background-image: url(https://picsum.photos/200/300?image=0);
  background-size: 100vw 100vh;
}

.reset img:hover {
  opacity: 1
}

.hiddenimage {
  position: absolute;
  top: 4.3vh;
  left: 50vw;
  cursor: pointer;
}

.hiddenimage img {
  width: 10.3vw;
  height: 10.5vh;
  border-radius: 15%;
}

.hand {
  position: absolute;
  top: 45.3vh;
  left: 17vw;
  cursor: pointer;
}

.hand img {
  width: 25.3vw;
  height: 25.5vh;
  border-radius: 0%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="main">
<div class="container2">
  <div class="containerr">
    <div class="pic" id="content">


      <div id="container">

        <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10" style="">
          <p name="values"></p>
        </div>
        <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
          <p name="values"></p>
        </div>
        <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
          <p name="values"></p>
        </div>
      </div>

    </div>
  </div>
</div>

<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
  <img src="" draggable="true" id="slide" border="rounded" />
</div>

<div class="congrats">
  <div class="hiddenimage" style="display:none;">
    <img src="" id="hiddenimageid" />
  </div>
</div>
</body>

Upvotes: 2

Related Questions