S
S
Sergey Goryachev2015-11-25 08:59:00
css
Sergey Goryachev, 2015-11-25 08:59:00

How to simplify this JS code?

I have a bunch of areas with data attributes.

<area shape="poly" coords="511,133,511,152,509,152,506,152,506,215,506,278,529,278,552,278,552,297,552,316,568,316,583,316,583,398,583,479,621,479,658,479,658,316,658,152,656,152,654,152,654,133,654,114,583,114,511,114" id="flat-0" class="flat-section" data-flat-number="123" data-flat-roomamount="2" data-flat-square="150,55">

Values ​​are obtained from the data attributes:
var flatNumber = $('#flat-0').data('flatNumber');
var flatRoomamount = $('#flat-0').data('flatRoomamount');
var flatSquare = $('#flat-0').data('flatSquare');

Then this data is passed to the div:
$('#flat-number-0').text(flatNumber);
$('#flat-roomamount-0').text(flatRoomamount);
$('#flat-square-0').text(flatSquare);

When hovering over area #flat-0, the block should be shown.
$('#flat-0').mousemove(function(e){ $('#flat-info-0').css({ display:"block" }); });
$('#flat-0').mouseout(function(){ $('#flat-info-0').css({ display:"none" }); });

Now I have 7 areas and for each #flat-1, #flat-2, #flat-3... #flat-7 all the code is written by handles.
<div id="flat-info-0" class="flat_mini_info">
   <div class="number">
      <span>№ квартиры</span>
      <span id="flat-number-0"></span>
   </div>
   <div class="roomamount">
      <span>Количество комнат</span>
      <span id="flat-roomamount-0"></span>
   </div>
   <div class="square">
      <span>Площадь, м<sup>2</sup></span>
      <span id="flat-square-0"></span>
   </div>
</div>


How to simplify this code?
I understand that this is a bug)))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Zuev, 2015-11-25
@webirus

codepen.io/anon/pen/qOGvyz

E
Ernest Faizullin, 2015-11-25
@erniesto77

more or less like this

var Flat = function(id) {

  this.$flat = $('#flat-'+id);

  this.flatNumber = this.$flat.data('flatNumber');
  this.flatRoomamount = this.$flat.data('flatRoomamount');
  this.flatSquare = this.$flat.data('flatSquare');

  $('#flat-number'+id).text(this.flatNumber);
  $('#flat-roomamount'+id).text(this.flatRoomamount);
  $('#flat-square'+id).text(this.flatSquare);

  this.$flat.hover(function() {
    $('#flat-info'+id).css({ display:"block" });
  }, function() {
    $('#flat-info'+id).css({ display:"none" });
  });
}


jQuery(document).ready(function($) {
  
  $('.flat-section').each(function(index, el) {
    new Flat(index);
  });
});

Learn more about Constructor Functions here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question