ttct ttct - 4 months ago 6
jQuery Question

Creating a jquery element from two other elements (code explanation request)

I was wondering if someone could explain the following lines to me:

var panel = parseInt($el.parent().attr('data-panel'));
var $curr_panel = $('.h5p-panel:eq(' + panel + ')', that.$myDom);
var $next_panel = $('.h5p-panel:eq(' + (panel + 1) + ')', that.$myDom);


If someone could walk me through it in simple english I would really appreciate it.

I understand that $curr_panel and $next_panel are created by the combination of an element in h5p panel and a dom element, but thereafter I'm a quite confused.

The code can be found here:

https://github.com/h5p/h5p-summary/blob/master/js/summary.js#L222

And a live demo here:

https://h5p.org/summary

Answer

You need to understand before :

  1. that => refres to an instance of Summary class.

    119   Summary.prototype.createQuestion = function() {
    120        var that = this;
    
  2. that.$myDom => jQuery element <div class="summary-content"/>

     124 this.$myDom = $('<div>', {
     125       'class': 'summary-content'
     126   });
    
  3. $(A,B) => means select A where B is one of its parents (context). [same B.find(A)]

  4. $('.CLASS:eq(i)',B) => means select the (i+1) element has Css class CLASS & one of its parents is B.

Conclusion :

$curr_panel = $('.h5p-panel:eq(' + panel + ')', that.$myDom);

Means, select DOM element where :

  • has Css class= h5p-panel
  • the 3rd element , if we assume panel=2 . (because eq(0) => 1st element)
  • one of its parents is that.$myDom