Class: Element

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/opal/jquery/element.rb

Overview

Element is a toll-free bridged class that maps to native jQuery instances.

As Element maps to a jQuery object, it can be used to represent 0, 1, or more actual DOM elements. Element exposes a more ruby-esqe interface to jQuery.

Usage

Element instances can be created in a number of ways.

Creating new Elements

A new element can be created using the Element.new method.

el = Element.new(:div)
el.id = "title"
p el
# => #<Element [<div id="title">]>

This is a nicer version of creating a javascript element using document.createElement and then wrapping it in a jquery object.

Finding existing elements in dom

Any valid jQuery selector expressions can be used with either Element.find or Element.[].

foos = Element.find('.foo')
# => #<Element [<div class="foo">]>

links = Element['a']
# => #<Element [<a>, <a class="bar">]>

Alternatively, Element.id can be used to find an element by its document id (or nil is returned for no match).

bar = Element.id 'bar'
# => Element or nil

DOM Content from string

Finally, an Element instance can be created by parsing a string of html content. This will parse multiple elements, like jquery, if string content contains them:

Element.parse '<div id="title">hello world</div>'
# => #<Element [<div id="title">]>

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#selectorObject (readonly)


135
136
137
# File 'lib/opal/jquery/element.rb', line 135

def selector
  @selector
end

Class Method Details

.[](selector) ⇒ Element

Find elements by the given css selector.

Returns an empty Element if no matching elements.


73
74
75
# File 'lib/opal/jquery/element.rb', line 73

def self.[](selector)
  `$(#{selector})`
end

.expose(*methods) ⇒ Object

Expose jQuery plugins to become available in ruby code. By default, jQuery methods or plugins must be manually exposed as ruby methods. This method simply creates an aliasing ruby method to call the original javascript function.

Examples:

# Expose bootstraps jQuery `modal` function
Element.expose :modal

Element.find('.my-modal').modal

128
129
130
131
132
# File 'lib/opal/jquery/element.rb', line 128

def self.expose(*methods)
  methods.each do |method|
    alias_native method
  end
end

.find(selector) ⇒ Element

Find elements by the given css selector.

Returns an empty Element if no matching elements.


63
64
65
# File 'lib/opal/jquery/element.rb', line 63

def self.find(selector)
  `$(#{selector})`
end

.id(id) ⇒ Element?

Find an element by the given id.

If no matching element, then nil will be returned. A matching element becomes the sole element in the returned collection.


84
85
86
87
88
89
90
91
92
93
94
# File 'lib/opal/jquery/element.rb', line 84

def self.id(id)
  %x{
    var el = document.getElementById(id);

    if (!el) {
      return nil;
    }

    return $(el);
  }
end

.new(tag = 'div') ⇒ Element

Create a new dom element, wrapped as Element instance with the given tag name.


101
102
103
# File 'lib/opal/jquery/element.rb', line 101

def self.new(tag = 'div')
  `$(document.createElement(tag))`
end

.parse(str) ⇒ Element

Parse a string of html content into an Element instance.

If no valid elements in string, then an empty collection will be returned.


111
112
113
# File 'lib/opal/jquery/element.rb', line 111

def self.parse(str)
  `$(str)`
end

Instance Method Details

#[](name) ⇒ Object


386
387
388
# File 'lib/opal/jquery/element.rb', line 386

def [](name)
  `self.attr(name) || nil`
end

#[]=(attr, value) ⇒ Object

Set the given attribute attr on each element in this collection.


304
# File 'lib/opal/jquery/element.rb', line 304

alias_native :[]=, :attr

#add_class(class_name) ⇒ Object


307
# File 'lib/opal/jquery/element.rb', line 307

alias_native :add_class, :addClass

#after(content) ⇒ Object

Inserts the given content after each element in this set of elements. This method can accept either another Element, or a string.


143
# File 'lib/opal/jquery/element.rb', line 143

alias_native :after

#animate(params, &block) ⇒ Object

Set css values over time to create animations. The first parameter is a set of css properties and values to animate to. The first parameter also accepts a special :speed value to set animation speed. If a block is given, the block is run as a callback when the animation finishes.


477
478
479
480
481
482
483
484
# File 'lib/opal/jquery/element.rb', line 477

def animate(params, &block)
  speed = params.has_key?(:speed) ? params.delete(:speed) : 400
  %x{
    self.animate(#{params.to_n}, #{speed}, function() {
      #{block.call if block_given?}
    })
  }
end

#any?true, false

Returns true if this collection has 1 or more elements, false otherwise.


602
603
604
# File 'lib/opal/jquery/element.rb', line 602

def any?
  `self.length > 0`
end

#append(content) ⇒ Object Also known as: <<


245
# File 'lib/opal/jquery/element.rb', line 245

alias_native :append

#append_to(element) ⇒ Object


310
# File 'lib/opal/jquery/element.rb', line 310

alias_native :append_to, :appendTo

#append_to_bodyObject


402
403
404
# File 'lib/opal/jquery/element.rb', line 402

def append_to_body
  `self.appendTo(document.body)`
end

#append_to_headObject


406
407
408
# File 'lib/opal/jquery/element.rb', line 406

def append_to_head
  `self.appendTo(document.head)`
end

#at(index) ⇒ Element?

Returns the element at the given index as a new Element instance. Negative indexes can be used and are counted from the end. If the given index is outside the range then nil is returned.


416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/opal/jquery/element.rb', line 416

def at(index)
  %x{
    var length = self.length;

    if (index < 0) {
      index += length;
    }

    if (index < 0 || index >= length) {
      return nil;
    }

    return $(self[index]);
  }
end

#attr(name, value = nil) ⇒ Object


390
391
392
393
394
395
396
# File 'lib/opal/jquery/element.rb', line 390

def attr(name, value=nil)
  if value.nil?
    `self.attr(name) || nil`
  else
    `self.attr(name, value)`
  end
end

#before(content) ⇒ Object

Insert the given content before each element in this set of elements. The given content can be either an Element, or a string.


151
# File 'lib/opal/jquery/element.rb', line 151

alias_native :before

#blurObject


200
# File 'lib/opal/jquery/element.rb', line 200

alias_native :blur

#children(selector = nil) ⇒ Object


197
# File 'lib/opal/jquery/element.rb', line 197

alias_native :children

#class_nameString

Returns the CSS class name of the firt element in self collection. If the collection is empty then an empty string is returned. Only the class name of the first element will ever be returned.


437
438
439
440
441
442
# File 'lib/opal/jquery/element.rb', line 437

def class_name
  %x{
    var first = self[0];
    return (first && first.className) || "";
  }
end

#class_name=(name) ⇒ Object

Sets the CSS class name of every element in self collection to the given string. self does not append the class names, it replaces the entire current class name.


449
450
451
452
453
454
455
456
# File 'lib/opal/jquery/element.rb', line 449

def class_name=(name)
  %x{
    for (var i = 0, length = self.length; i < length; i++) {
      self[i].className = name;
    }
  }
  self
end

#cloneElement

Clone all elements inside this collection, and return as a new instance.


281
# File 'lib/opal/jquery/element.rb', line 281

alias_native :clone

#closest(selector) ⇒ Object


203
# File 'lib/opal/jquery/element.rb', line 203

alias_native :closest

#css(name, value = nil) ⇒ Object

Get or set css properties on each element in self collection. If only the name is given, then that css property name is read from the first element in the collection and returned. If the value property is also given then the given css property is set to the given value for each of the elements in self collection. The property can also be a hash of properties and values.


464
465
466
467
468
469
470
471
# File 'lib/opal/jquery/element.rb', line 464

def css(name, value=nil)
  if value.nil? && name.is_a?(String)
    return `self.css(name)`
  else
    name.is_a?(Hash) ? `self.css(#{name.to_n})` : `self.css(name, value)`
  end
  self
end

#data(*args) ⇒ Object


486
487
488
489
490
491
# File 'lib/opal/jquery/element.rb', line 486

def data(*args)
  %x{
    var result = self.data.apply(self, args);
    return result == null ? nil : result;
  }
end

#detach(selector = nil) ⇒ Object


206
# File 'lib/opal/jquery/element.rb', line 206

alias_native :detach

#each {|`$(self[i])`| ... } ⇒ Object

Yields:

  • (`$(self[i])`)

511
512
513
514
515
516
# File 'lib/opal/jquery/element.rb', line 511

def each
  `for (var i = 0, length = self.length; i < length; i++) {`
    yield `$(self[i])`
  `}`
  self
end

#effect(name, *args, &block) ⇒ Object

Start a visual effect (e.g. fadeIn, fadeOut, …) passing its name. Underscored style is automatically converted (e.g. effect(:fade_in)). Also accepts additional arguments and a block for the finished callback.


496
497
498
499
500
501
# File 'lib/opal/jquery/element.rb', line 496

def effect(name, *args, &block)
  name = name.gsub(/_\w/) { |match| match[1].upcase }
  args = args.map { |a| a.to_n if a.respond_to? :to_n }.compact
  args << `function() { #{block.call if block_given?} }`
  `self[#{name}].apply(self, #{args})`
end

#emptyObject

Remove all child nodes from each element in this collection.


286
# File 'lib/opal/jquery/element.rb', line 286

alias_native :empty

#fade_toggle(duration = 400) ⇒ Object


368
# File 'lib/opal/jquery/element.rb', line 368

alias_native :fade_toggle, :fadeToggle

#filter(selector) ⇒ Element


257
# File 'lib/opal/jquery/element.rb', line 257

alias_native :filter

#find(selector) ⇒ Object


212
# File 'lib/opal/jquery/element.rb', line 212

alias_native :find

#firstObject


518
519
520
# File 'lib/opal/jquery/element.rb', line 518

def first
  `self.length ? self.first() : nil`
end

#focusObject


209
# File 'lib/opal/jquery/element.rb', line 209

alias_native :focus

#getObject


289
# File 'lib/opal/jquery/element.rb', line 289

alias_native :get

#has_attribute?(name) ⇒ Boolean


398
399
400
# File 'lib/opal/jquery/element.rb', line 398

def has_attribute?(name)
  `!!self.attr(name)`
end

#has_class?(class_name) ⇒ Object


313
# File 'lib/opal/jquery/element.rb', line 313

alias_native :has_class?, :hasClass

#heightObject


658
659
660
# File 'lib/opal/jquery/element.rb', line 658

def height
  `self.height() || nil`
end

#height=(value) ⇒ Object


371
# File 'lib/opal/jquery/element.rb', line 371

alias_native :height=, :height

#hide(duration = 400) ⇒ Object


188
# File 'lib/opal/jquery/element.rb', line 188

alias_native :hide

#html(content = undefined) ⇒ Object


522
523
524
525
526
527
528
529
530
# File 'lib/opal/jquery/element.rb', line 522

def html(content = undefined)
  %x{
    if (content != null) {
      return self.html(content);
    }

    return self.html() || '';
  }
end

#html=(content) ⇒ Object

Set the html content of each element in this collection to the passed content. Content can either be a string or another Element.


321
# File 'lib/opal/jquery/element.rb', line 321

alias_native :html=, :html

#idObject


532
533
534
535
536
537
# File 'lib/opal/jquery/element.rb', line 532

def id
  %x{
    var first = self[0];
    return (first && first.id) || "";
  }
end

#id=(id) ⇒ Object


539
540
541
542
543
544
545
546
547
548
549
# File 'lib/opal/jquery/element.rb', line 539

def id=(id)
  %x{
    var first = self[0];

    if (first) {
      first.id = id;
    }

    return self;
  }
end

#inspectObject


555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/opal/jquery/element.rb', line 555

def inspect
  %x{
    if      (self[0] === document) return '#<Element [document]>'
    else if (self[0] === window  ) return '#<Element [window]>'

    var val, el, str, result = [];

    for (var i = 0, length = self.length; i < length; i++) {
      el  = self[i];
      if (!el.tagName) { return '#<Element ['+el.toString()+']'; }

      str = "<" + el.tagName.toLowerCase();

      if (val = el.id) str += (' id="' + val + '"');
      if (val = el.className) str += (' class="' + val + '"');

      result.push(str + '>');
    }

    return '#<Element [' + result.join(', ') + ']>';
  }
end

#is(selector) ⇒ true, false


252
# File 'lib/opal/jquery/element.rb', line 252

alias_native :is

#lastElement

Returns a new Element instance containing the last element in this current set.


265
# File 'lib/opal/jquery/element.rb', line 265

alias_native :last

#lengthInteger Also known as: size

Returns the number of elements in this collection. May be zero.


594
595
596
# File 'lib/opal/jquery/element.rb', line 594

def length
  `self.length`
end

#next(selector = nil) ⇒ Object Also known as: succ


215
# File 'lib/opal/jquery/element.rb', line 215

alias_native :next

#off(name, sel, block = nil) ⇒ Object


638
639
640
641
642
643
644
645
646
647
648
649
650
# File 'lib/opal/jquery/element.rb', line 638

def off(name, sel, block = nil)
  %x{
    if (sel == null) {
      return self.off(name);
    }
    else if (block === nil) {
      return self.off(name, sel._jq_wrap);
    }
    else {
      return self.off(name, sel, block._jq_wrap);
    }
  }
end

#offsetObject


507
508
509
# File 'lib/opal/jquery/element.rb', line 507

def offset
  Native(`self.offset()`)
end

#on(name, sel = nil, &block) ⇒ Object


615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
# File 'lib/opal/jquery/element.rb', line 615

def on(name, sel = nil, &block)
  %x{
    var wrapper = function(evt) {
      if (evt.preventDefault) {
        evt = #{Event.new `evt`};
      }

      return block.apply(null, arguments);
    };

    block._jq_wrap = wrapper;

    if (sel == nil) {
      self.on(name, wrapper);
    }
    else {
      self.on(name, sel, wrapper);
    }
  }

  block
end

#outer_height(include_margin = false) ⇒ Object


380
# File 'lib/opal/jquery/element.rb', line 380

alias_native :outer_height, :outerHeight

#outer_width(include_margin = false) ⇒ Object


377
# File 'lib/opal/jquery/element.rb', line 377

alias_native :outer_width, :outerWidth

#parent(selector = nil) ⇒ Element

Returns a new Element set with the parents of each element in this collection. An optional selector argument can be used to filter the results to match the given selector. Result may be empty.


161
# File 'lib/opal/jquery/element.rb', line 161

alias_native :parent

#parents(selector = nil) ⇒ Element

Returns a new Element set with all parents of each element in this collection. An optional selector may be provided to filter the selection. Resulting collection may be empty.

Examples:

Without filtering collection

Element.find('#foo').parents
# => #<Element [<div id="wrapper">, <body>, <html>]>

Using a filter

Element.find('#foo').parents('div')
# => #<Element [<div id="wrapper">]

179
# File 'lib/opal/jquery/element.rb', line 179

alias_native :parents

#positionObject


666
667
668
# File 'lib/opal/jquery/element.rb', line 666

def position
  Native(`self.position()`)
end

#prev(selector = nil) ⇒ Object


182
# File 'lib/opal/jquery/element.rb', line 182

alias_native :prev

#prop(name, value = nil) ⇒ Object

Get or set the property name on each element in collection.


294
# File 'lib/opal/jquery/element.rb', line 294

alias_native :prop

#remove(selector = nil) ⇒ Object


185
# File 'lib/opal/jquery/element.rb', line 185

alias_native :remove

#remove_attr(attr) ⇒ Object


324
# File 'lib/opal/jquery/element.rb', line 324

alias_native :remove_attr, :removeAttr

#remove_attribute(attr) ⇒ Object


356
# File 'lib/opal/jquery/element.rb', line 356

alias_native :remove_attribute, :removeAttr

#remove_class(class_name) ⇒ Object


327
# File 'lib/opal/jquery/element.rb', line 327

alias_native :remove_class, :removeClass

#scroll_leftObject


353
# File 'lib/opal/jquery/element.rb', line 353

alias_native :scroll_left, :scrollLeft

#scroll_left=(value) ⇒ Object


350
# File 'lib/opal/jquery/element.rb', line 350

alias_native :scroll_left=, :scrollLeft

#scroll_topObject


347
# File 'lib/opal/jquery/element.rb', line 347

alias_native :scroll_top, :scrollTop

#scroll_top=(value) ⇒ Object


344
# File 'lib/opal/jquery/element.rb', line 344

alias_native :scroll_top=, :scrollTop

#serializeObject


248
# File 'lib/opal/jquery/element.rb', line 248

alias_native :serialize

#show(duration = 400) ⇒ Object


191
# File 'lib/opal/jquery/element.rb', line 191

alias_native :show

#siblings(selector = nil) ⇒ Object


218
# File 'lib/opal/jquery/element.rb', line 218

alias_native :siblings

#slide_down(duration = 400) ⇒ Object


359
# File 'lib/opal/jquery/element.rb', line 359

alias_native :slide_down, :slideDown

#slide_toggle(duration = 400) ⇒ Object


365
# File 'lib/opal/jquery/element.rb', line 365

alias_native :slide_toggle, :slideToggle

#slide_up(duration = 400) ⇒ Object


362
# File 'lib/opal/jquery/element.rb', line 362

alias_native :slide_up, :slideUp

#stopObject

Stop any currently running animations on element.


275
# File 'lib/opal/jquery/element.rb', line 275

alias_native :stop

#tag_nameObject


551
552
553
# File 'lib/opal/jquery/element.rb', line 551

def tag_name
  `self.length > 0 ? self[0].tagName.toLowerCase() : #{nil}`
end

#text(text = nil) ⇒ String

Get or set the text content of each element in this collection. Setting the content is provided as a compatibility method for jquery. Instead #text= should be used for setting text content.

If no text content is provided, then the text content of this element will be returned.

See Also:


232
# File 'lib/opal/jquery/element.rb', line 232

alias_native :text

#text=(text) ⇒ Object

Set text content of each element in this collection.

See Also:


335
# File 'lib/opal/jquery/element.rb', line 335

alias_native :text=, :text

#to_nObject


382
383
384
# File 'lib/opal/jquery/element.rb', line 382

def to_n
  self
end

#to_sObject


578
579
580
581
582
583
584
585
586
587
588
589
590
# File 'lib/opal/jquery/element.rb', line 578

def to_s
  %x{
    var val, el, result = [];

    for (var i = 0, length = self.length; i < length; i++) {
      el  = self[i];

      result.push(el.outerHTML)
    }

    return result.join(', ');
  }
end

#toggle(duration = 400) ⇒ Object


194
# File 'lib/opal/jquery/element.rb', line 194

alias_native :toggle

#toggle_classObject


338
# File 'lib/opal/jquery/element.rb', line 338

alias_native :toggle_class, :toggleClass

#trigger(event) ⇒ Object

Trigger an event on this element. The given event specifies the event type.


240
# File 'lib/opal/jquery/element.rb', line 240

alias_native :trigger

#valueObject


654
655
656
# File 'lib/opal/jquery/element.rb', line 654

def value
  `self.val() || ""`
end

#value=(value) ⇒ Object


341
# File 'lib/opal/jquery/element.rb', line 341

alias_native :value=, :val

#visible?Boolean


503
504
505
# File 'lib/opal/jquery/element.rb', line 503

def visible?
  `self.is(':visible')`
end

#widthObject


662
663
664
# File 'lib/opal/jquery/element.rb', line 662

def width
  `self.width() || nil`
end

#width=(value) ⇒ Object


374
# File 'lib/opal/jquery/element.rb', line 374

alias_native :width=, :width

#wrap(wrapper) ⇒ Element


270
# File 'lib/opal/jquery/element.rb', line 270

alias_native :wrap