Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set the page-break behavior before an element with JavaScript?
Use the pageBreakBefore property in JavaScript to set the page-break behavior before an element. Use the always property to insert a page break before an element.
Note ? The changes would be visible while printing or viewing the print preview.
Syntax
element.style.pageBreakBefore = "value";
Property Values
| Value | Description |
|---|---|
auto |
Default - automatic page break |
always |
Always insert page break before element |
avoid |
Avoid page break before element |
left |
Insert page break to start on left page |
right |
Insert page break to start on right page |
Example
You can try to run the following code to set the page-break behavior before an element with JavaScript:
<!DOCTYPE html>
<html>
<body>
<h1>Heading 1</h1>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p id="myFooter">This is footer text.</p>
<button type="button" onclick="display()">Set page-break</button>
<script>
function display() {
document.getElementById("myFooter").style.pageBreakBefore = "always";
alert("Page break set! Check print preview (Ctrl+P)");
}
</script>
</body>
</html>
How It Works
When you click the button, JavaScript sets the pageBreakBefore property to "always" for the footer element. This forces a page break before the footer when printing. The effect is only visible in print preview or actual printing.
Practical Use Case
<!DOCTYPE html>
<html>
<body>
<div>Content page 1</div>
<div id="chapter2">Chapter 2 starts here</div>
<button onclick="addPageBreak()">Start Chapter 2 on new page</button>
<script>
function addPageBreak() {
document.getElementById("chapter2").style.pageBreakBefore = "always";
console.log("Page break added before Chapter 2");
}
</script>
</body>
</html>
Conclusion
The pageBreakBefore property controls page breaks in printed documents. Use "always" to force page breaks before specific elements, which is useful for chapter headings or section separators.
