0

This is my part of code, I've created an object and now I want to hide all those elements in object, since I'm making the animation for the web page. How to achieve this, please help me?!

var rightPart = $('.anotherOne');
var numberOfLines = { 
    first : $('#caption_1'),
    second : $('#caption_2'),
    third : $('#caption_3')
 }
for (var key in numberOfLines) {
    hide(numberOfLines);
}
Jehnsen Marshal
  • 113
  • 1
  • 2
  • 10

3 Answers3

3

For-in loop is used to iterate object keys and property of the key is accessed using Object[key]

var rightPart = $('.anotherOne');
var numberOfLines = {
  first: $('#caption_1'),
  second: $('#caption_2'),
  third: $('#caption_3')
}
for (var key in numberOfLines) {
  numberOfLines[key].hide(); //numberOfLines[key] holds the `$('#caption_1')...` elements
}
Rayon
  • 36,219
  • 4
  • 49
  • 76
1

I would recommend to use jquery each in your case. It iterates over an object, but does not have any of the side effects like for-in. Normally, with for-in you have to consider the object's own properties. (See here what is an “OWN” property in javascript)

$.each(numberOfLines, function (line) {
    line.hide();
});
mos
  • 83
  • 7
1

You just need to push only id value in dictionary rather than jquery code in values against keys.

I put value of id in dictionary. In the for loop, iterate only id's values and do as usually to refer selector ID to refer the corressponding element and it'll work. Same goes for $('#caption_1') in the first line.

var rightPart = $('.anotherOne');
    var numberOfLines = {
      first: 'caption_1',
      second: 'caption_2',
      third: 'caption_3'
    };
    for(var key in numberOfLines) {
      $('#'+numberOfLines[key]).hide(); 
    }
Nelson
  • 2,040
  • 17
  • 23
alfishan aqeel
  • 220
  • 2
  • 5
  • Please try to avoid just dumping code as an answer and try to explain what it does and why. Your code might not be obvious for people who do not have the relevant coding experience. Please edit your answer to include [clarification, context and try to mention any limitations, assumptions or simplifications in your answer.](https://stackoverflow.com/help/how-to-answer) – Frits Jun 30 '17 at 10:27