Skip to content

Commit

Permalink
Add onclick attribute to HTML nodes (#43)
Browse files Browse the repository at this point in the history
Makes onclick a first class attribute on HTML body nodes.
  • Loading branch information
8W9aG authored May 7, 2020
1 parent 841fc5c commit 9e53175
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
11 changes: 11 additions & 0 deletions Sources/Plot/API/HTMLAttributes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,17 @@ public extension Node where Context == HTML.ScriptContext {
}
}

// MARK: - Javascript

public extension Node where Context: HTML.BodyContext {
/// Add a script to execute when the user clicks the current element.
/// - parameter script: The script to execute when the user clicks on the node.
/// Usually prefixed with `javascript:`.
static func onclick(_ script: String) -> Node {
.attribute(named: "onclick", value: script)
}
}

// MARK: - Other, element-specific attributes

public extension Node where Context == HTML.AbbreviationContext {
Expand Down
16 changes: 15 additions & 1 deletion Tests/PlotTests/HTMLTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,19 @@ final class HTMLTests: XCTestCase {
</picture></body>
""")
}

func testOnClick() {
let html = HTML(
.body(
.div(
.onclick("javascript:alert('Hello World')")
)
)
)
assertEqualHTMLContent(html, """
<body><div onclick="javascript:alert('Hello World')"></div></body>
""")
}
}

extension HTMLTests {
Expand Down Expand Up @@ -738,7 +751,8 @@ extension HTMLTests {
("testDataAttributes", testDataAttributes),
("testSubresourceIntegrity", testSubresourceIntegrity),
("testComments", testComments),
("testPicture", testPicture)
("testPicture", testPicture),
("testOnClick", testOnClick)
]
}
}

0 comments on commit 9e53175

Please sign in to comment.