Module: Browser::DocumentMethods

Defined in:
lib/opal/jquery/document.rb

Overview

Document includes these methods to extend Element.

Generally, you will want to use the Document top level instance of Element.

Usage

A useful method on Document is the #ready? method, which can be used to run a block once the document is ready. This is equivalent to passing a function to the jQuery constructor. Unlike jQuery it will work correctly even if called after the document is already loaded.

Document.ready? do
  puts "Page is ready to use!"
end

Just like jQuery, multiple blocks may be passed to #ready?.

Document.ready (without the question mark) returns the equivilent promise. Like other promises it can be combined using the when and then methods.

Document.ready.then do |ready|
  puts "Page is ready to use!"
end

Document head and body elements

Every document has atleast two elements: a head and body. For convenience, these are both exposed as #head and #body respectively, and are just instances of Element.

puts Document.head
puts Document.body

# => #<Element: [<head>]>
# => #<Element: [<body>]>

Events

Document instances also have #on, #off and #trigger methods for handling events. These all just delegate to their respective methods on Element, using document as the context.

Document.on :click do |evt|
  puts "someone clicked somewhere in the document"
end

Constant Summary collapse

@@__isReady =
false

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.ready?(&block) ⇒ Boolean

Register a block to run once the document/page is ready. will call the block if the document is already ready

Examples:

Document.ready? do
  puts "ready to go"
end

Returns:

  • (Boolean)


67
68
69
# File 'lib/opal/jquery/document.rb', line 67

def ready?(&block)
  @@__isReady ? block.call : `$(#{block})` if block_given?
end

Instance Method Details

#bodyElement

Element instance wrapping document.body.

Returns:



112
113
114
# File 'lib/opal/jquery/document.rb', line 112

def body
  Element.find `document.body`
end

#headElement

Element instance wrapping document.head.

Returns:



105
106
107
# File 'lib/opal/jquery/document.rb', line 105

def head
  Element.find `document.head`
end

#readyObject

Return a promise that resolves when the document is ready.

Examples:

Document.ready.then do |r|
  puts "ready to go"
end


78
79
80
81
82
# File 'lib/opal/jquery/document.rb', line 78

def ready
  promise = Promise.new
  Document.ready? { promise.resolve }
  promise
end

#titleString

Returns document title.

Returns:

  • (String)


91
92
93
# File 'lib/opal/jquery/document.rb', line 91

def title
  `document.title`
end

#title=(title) ⇒ Object

Set document title.

Parameters:

  • title (String)


98
99
100
# File 'lib/opal/jquery/document.rb', line 98

def title=(title)
  `document.title = title`
end