How to add only one element of 4 to another div using jQuery

Hello I am learning jQuery for students and my goal is to move an element (only one character) by clicking on the specified "#chosen" area and the rest will remain (since I will be adding a second selection after this step). However, when one of the characters is clicked, all characters go to that '#chosen' div. I know my code is wrong and incomplete, but I just don't know how to fix it or how to split the elements, because they all have the same class. Thanks for any help or advanced hints, I really appreciate it.

JS:

$(document).ready(function() {

//Audio
// var audioElement = $('audio');
//  audioElement.attr('src', 'assets/mp3/cantina.mp3');
//  audioElement.attr('autoplay', 'autoplay');
//  audioElement.loop = true; 

//Objects
var hansolo = {
    name: "Han Solo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/hansolo.jpg",
}

var chewy = {
    name: "Chewy",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/chewy.jpg",
}

var jabba = {
    name: "Jabba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/jabba.jpg",
}

var greedo = {
    name: "Greedo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/greedo.jpg",
}

var choices = [hansolo, chewy, jabba, greedo];

var charOptionsRow = $('#charOptions');
    $.each(choices, function(index, choice) {
      // Create a new div.col-lg-3 to be appended to row.
      var charOptionCol = $('<div>')
        .addClass('char-option col-lg-3');

      // Append image to col.
      var charImg = $('<img>')
        .addClass('char-img')
        .attr('src', choice.src);
      charOptionCol.append(charImg);

      // Append text to col.
      var charText = $('<h3>')
        .addClass('char-text')
        .text(choice.name);
      charOptionCol.append(charText);

      // Append column to row.
      charOptionsRow.append(charOptionCol);
});

$(document).on('click', '.char-img', 'char-text', function() {
    if (hansolo) {
        var charPick =$("#chosen");
        $('.char-img').appendTo(charPick);
        $('.char-text').appendTo(charPick);
    }
    if (chewy) {
        var charPick =$("#chosen");
        $('.char-img').appendTo(charPick);
        $('.char-text').appendTo(charPick);
    }
    if (jabba) {
        var charPick =$("#chosen");
        $('.char-img').appendTo(charPick);
        $('.char-text').appendTo(charPick);
    }
    if (greedo) {
        var charPick =$("#chosen");
        $('.char-img').appendTo(charPick);
        $('.char-text').appendTo(charPick);
    }
});
});

      

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>JQuery Game</title>

        <link rel="stylesheet" type="text/css" href="assets/css/reset.css">
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="assets/css/style.css">
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
    </head>
<body>

    <div class="container" style="max-width:800px;">
        <h1 align="center">Star Wars Game</h1>
        <h2 align="center" id="character-text">Choose your character:</h2>
        <div class="row" id="charOptions" style="max-width:800px;" align="center">
        </div>

        <div class="row" align="center" style="max-width:800px;">
            <!-- Choice Header -->
            <div class="col-lg-6 you" id="chosen" align="center">
                <h2 align="center" id="chosen-text" class="hidden">You</h2>
            </div>
            <!-- First Enemy Header -->
            <div class="col-lg-6 fighting" align="center">
                <h2 align="center" id="chosen-text" class="hidden">Fighting</h2>
            </div>
        </div>
        <div class="row" align="center" style="max-width:800px;">
            <!-- Enemies Header-->
            <div class="col-lg-12" id="enemies" align="center">
                <h2 align="center" id="enemies-text" class="hidden">Your Enemies</h2>
            </div>
        </div>  
            <div class="row" align="center" style="max-width:800px;">
            <!-- Enemies -->
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
                    <div id="first-enemy"></div>
                </div>
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
                    <div id="second-enemy"></div>
                </div>
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
                    <div id="third-enemy"></div>
                </div>
            </div>

    </div>

<script src="assets/js/game.js"></script>
</body>

      

+3


source to share


4 answers


You move all the elements char-img

and char-text

(except for a few typos) at once - the links $('.char-img')

don't know that you only mean the one that was clicked.

Use instead this

to indicate which item was clicked. Then grab the adjacent text or image and move only those two.

$(document).on('click', '.char-img, .char-text', function() {
  var el = $(this),
      img, txt;

  if (el.hasClass('char-img')) {
    img = el;
    txt = el.next('.char-text');
  } else {
    txt = el;
    img = el.prev('.char-img');
  }

  $('#chosen').append(img).append(txt);
});

      



$(document).ready(function() {

  //Objects
  var hansolo = {
    name: "Han Solo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/hansolo.jpg",
  }

  var chewy = {
    name: "Chewy",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/chewy.jpg",
  }

  var jabba = {
    name: "Jabba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/jabba.jpg",
  }

  var greedo = {
    name: "Greedo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/greedo.jpg",
  }

  var choices = [hansolo, chewy, jabba, greedo];

  var charOptionsRow = $('#charOptions');
  $.each(choices, function(index, choice) {
    // Create a new div.col-lg-3 to be appended to row.
    var charOptionCol = $('<div>')
      .addClass('char-option col-lg-3');

    // Append image to col.
    var charImg = $('<img>')
      .addClass('char-img')
      .attr('src', choice.src);
    charOptionCol.append(charImg);

    // Append text to col.
    var charText = $('<h3>')
      .addClass('char-text')
      .text(choice.name);
    charOptionCol.append(charText);

    // Append column to row.
    charOptionsRow.append(charOptionCol);
  });

  $(document).on('click', '.char-img, .char-text', function() {
    var el = $(this),
      img, txt;
      
    if (el.hasClass('char-img')) {
      img = el;
      txt = el.next('.char-text');
    } else {
      txt = el;
      img = el.prev('.char-img');
    }

    $('#chosen').append(img).append(txt);
  });
});
      

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

<div class="container" style="max-width:800px;">
  <h1 align="center">Star Wars Game</h1>
  <h2 align="center" id="character-text">Choose your character:</h2>
  <div class="row" id="charOptions" style="max-width:800px;" align="center">
  </div>

  <div class="row" align="center" style="max-width:800px;">
    <!-- Choice Header -->
    <div class="col-lg-6 you" id="chosen" align="center">
      <h2 align="center" id="chosen-text" class="hidden">You</h2>
    </div>
    <!-- First Enemy Header -->
    <div class="col-lg-6 fighting" align="center">
      <h2 align="center" id="chosen-text" class="hidden">Fighting</h2>
    </div>
  </div>
  <div class="row" align="center" style="max-width:800px;">
    <!-- Enemies Header-->
    <div class="col-lg-12" id="enemies" align="center">
      <h2 align="center" id="enemies-text" class="hidden">Your Enemies</h2>
    </div>
  </div>
  <div class="row" align="center" style="max-width:800px;">
    <!-- Enemies -->
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
      <div id="first-enemy"></div>
    </div>
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
      <div id="second-enemy"></div>
    </div>
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
      <div id="third-enemy"></div>
    </div>
  </div>

</div>
      

Run code


+1


source


Instead of listening to "$ (document) .on (...", listening to $ (". Char-option"). On ("click", function () .... - then inside the function, $ (this ) will be the element that was clicked in. Instead of listening for click anywhere, this will allow you to listen for click events only on elements that have a char -option class.

In your if statement they will all be fixed to true. I understand the intent is "if hansolo was pressed then", but you are really asking "if hansolo is undefined".



Until I have given you everything, I hope this helps point you in the right direction.

0


source


In the click event, instead of using a selector, $('.char-img')

try using $(this)

.

Also, you don't need to check who was selected if you are going to run the same piece of code in every statement if

.

See if this works for you.

$(document).ready(function() {

  //Audio
  // var audioElement = $('audio');
  //  audioElement.attr('src', 'assets/mp3/cantina.mp3');
  //  audioElement.attr('autoplay', 'autoplay');
  //  audioElement.loop = true; 

  //Objects
  var hansolo = {
    name: "Han Solo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/7b72d15a85bf468d8af9c5b5699e02ca.png",
  };

  var chewy = {
    name: "Chewy",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/044c70c30f084ba095c35aa7e4451f0c.png",
  };

  var jabba = {
    name: "Jabba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/458ccfc9819f4f8b85116b81584f4eea.png",
  };

  var boba = {
    name: "Boba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/85458d08609f4170b5b8cdda58fca07c.png",
  };

  var choices = [hansolo, chewy, jabba, boba];

  var charOptionsRow = $('#charOptions');
  $.each(choices, function(index, choice) {
    // Create a new div.col-lg-3 to be appended to row.
    var charOptionCol = $('<div>')
      .addClass('char-option col-lg-3');

    // Append image to col.
    var charImg = $('<img>')
      .addClass('char-img')
      .attr('src', choice.src);
    charOptionCol.append(charImg);

    // Append text to col.
    var charText = $('<h3>')
      .addClass('char-text')
      .text(choice.name);
    charOptionCol.append(charText);

    // Append column to row.
    charOptionsRow.append(charOptionCol);
  });

  $('.char-option').on('click', function() {
    var $charPick = $("#chosen");
    var $chosen = $('#chosen-text');
    var $img = $(this).find('img').clone();
    var $header = $(this).find('h3').clone();
    var name = $header.text();

    $chosen.children('span').html(name);
    $chosen.removeClass('hidden');

    $charPick.find('img').remove();
    $charPick.find('h3').remove();
    $charPick.append($img).append($header);

    $('html, body').animate({
      scrollTop: $(document).height()
    });
  });
});
      

#chosen .char-img {
   border: 0.2em solid black;
}
      

<head>
  <meta charset="UTF-8">
  <title>JQuery Game</title>
  <link rel="stylesheet" type="text/css" href="assets/css/reset.css">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="assets/css/style.css">
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>

<body>
  <div class="container" style="max-width:800px;">
    <h1 align="center">Star Wars Game</h1>
    <h2 align="center" id="character-text">Choose your character:</h2>
    <div class="row" id="charOptions" style="max-width:800px;" align="center">
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Choice Header -->
      <div class="col-lg-6 you" id="chosen" align="center">
        <h2 align="center" id="chosen-text" class="hidden">You've chosen <span class="chosen-name"></span></h2>
      </div>
      <!-- First Enemy Header -->
      <div class="col-lg-6 fighting" align="center">
        <h2 align="center" id="chosen-text" class="hidden">Fighting</h2>
      </div>
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Enemies Header-->
      <div class="col-lg-12" id="enemies" align="center">
        <h2 align="center" id="enemies-text" class="hidden">Your Enemies</h2>
      </div>
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Enemies -->
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="first-enemy"></div>
      </div>
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="second-enemy"></div>
      </div>
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="third-enemy"></div>
      </div>
    </div>
  </div>
</body>
      

Run code


0


source


$(document).ready(function() {

  //Audio
  // var audioElement = $('audio');
  //  audioElement.attr('src', 'assets/mp3/cantina.mp3');
  //  audioElement.attr('autoplay', 'autoplay');
  //  audioElement.loop = true; 

  //Objects
  var hansolo = {
    name: "Han Solo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/7b72d15a85bf468d8af9c5b5699e02ca.png",
  };

  var chewy = {
    name: "Chewy",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/044c70c30f084ba095c35aa7e4451f0c.png",
  };

  var jabba = {
    name: "Jabba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/458ccfc9819f4f8b85116b81584f4eea.png",
  };

  var boba = {
    name: "Boba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/85458d08609f4170b5b8cdda58fca07c.png",
  };

  var choices = [hansolo, chewy, jabba, boba];

  var charOptionsRow = $('#charOptions');
  $.each(choices, function(index, choice) {
    // Create a new div.col-lg-3 to be appended to row.
    var charOptionCol = $('<div>')
      .addClass('char-option col-lg-3');

    // Append image to col.
    var charImg = $('<img>')
      .addClass('char-img')
      .attr('src', choice.src);
    charOptionCol.append(charImg);

    // Append text to col.
    var charText = $('<h3>')
      .addClass('char-text')
      .text(choice.name);
    charOptionCol.append(charText);

    // Append column to row.
    charOptionsRow.append(charOptionCol);
  });

  $('.char-img, .char-text').on('click', function() {
    $('#chosen-img').remove();
    $('#chosen').prepend('<img id="chosen-img"/>');
    $('#chosen-img').css({
      'border': '2px solid red'
    }).attr('src', $(this).parent().find('img').attr('src'));
    $('h2', '#chosen').text("You Choose: " + $(this).parent().find('.char-text').text()).removeClass('hidden').show();
    $("html, body").animate({
      scrollTop: $(document).height()
    }, 100);
    //console.log($(this).attr('src'));
    // console.log($(this).parent().find('.char-text').text());
  });
});
      

<head>
  <meta charset="UTF-8">
  <title>JQuery Game</title>
  <link rel="stylesheet" type="text/css" href="assets/css/reset.css">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="assets/css/style.css">
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>

<body>
  <div class="container" style="max-width:800px;">
    <h1 align="center">Star Wars Game</h1>
    <h2 align="center" id="character-text">Choose your character:</h2>
    <div class="row" id="charOptions" style="max-width:800px;" align="center">
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Choice Header -->
      <div class="col-lg-6 you" id="chosen" align="center">
        <h2 align="center" id="chosen-text" class="hidden">You</h2>
      </div>
      <!-- First Enemy Header -->
      <div class="col-lg-6 fighting" align="center">
        <h2 align="center" id="chosen-text" class="hidden">Fighting</h2>
      </div>
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Enemies Header-->
      <div class="col-lg-12" id="enemies" align="center">
        <h2 align="center" id="enemies-text" class="hidden">Your Enemies</h2>
      </div>
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Enemies -->
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="first-enemy"></div>
      </div>
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="second-enemy"></div>
      </div>
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="third-enemy"></div>
      </div>
    </div>
  </div>
</body>
      

Run code


0


source







All Articles