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

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)


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

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

Instance Method Details

#bodyElement

Element instance wrapping document.body.

Returns:



108
109
110
# File 'lib/opal/jquery/document.rb', line 108

def body
  Element.find `document.body`
end

#headElement

Element instance wrapping document.head.

Returns:



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

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


74
75
76
77
78
# File 'lib/opal/jquery/document.rb', line 74

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

#titleString

Returns document title.

Returns:

  • (String)


87
88
89
# File 'lib/opal/jquery/document.rb', line 87

def title
  `document.title`
end

#title=(title) ⇒ Object

Set document title.

Parameters:

  • title (String)


94
95
96
# File 'lib/opal/jquery/document.rb', line 94

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