iHL iHL - 6 months ago 20
HTML Question

Goto 'next' and 'previous' HTML elements within page using javascript

I have created a script which uses a global variable to define current shown section, run a function to add or subtract to it, and uses that value to goto next or previous element by displaying a specific section. Basically, multiple pages in one HTML file.

I have updated the page to include your suggestions.

HTML With In-line JavaScript

<html style="font-family:Segoe UI;font-size:150%;text-indent:2em;text-align:justify;color:000;background:FFF">
<body style="padding:1% 3% 3% 1%">
<section id='controls'>
<h1 id='prev' style="float:left;cursor:context-menu;color:#888" onclick="i('prev')">Prev Chapter</h1>
<h1 id='next' style="float:left;cursor:hand;color:#0F8" onclick="i('next')">Next Chapter</h1>
</section>
<section id='x0' class='x' style="display:block;cursor:context-menu">
<script>
var page = 0
var a = document.getElementById('prev');
var b = document.getElementById('next');
var c = document.getElementsByClassName('x');
function i(action) {
if (action == 'prev') {
if (page == 0) {
a.style.cursor = 'context-menu';
a.style.color = '#FFF';
} else {
a.style.cursor = 'hand';
a.style.color = '#08F';
page = page - 1
}
}
if (action == 'next') {
if (page == 0) {
b.style.cursor = 'context-menu';
b.style.color = '#FFF';
} else {
b.style.cursor = 'hand';
b.style.color = '#0F8';
page = page + 1
}
}
for (var i = 0; i < c.length; ++i) {c[i].style.display = 'none';}
document.getElementById('x'+page).style.display = 'block';
}

</script>
</body>
</html>

Answer

The reason javascript dose not care about the action is because you are using the wrong operator. Try using == operator in order to make an expression that returns a boolean value. You can reference operators usage here

Also consider a conditional statement to not let the page variable go out of the needed bounds for your algorythim (for example -1). And Also consider loading the script at the end of the <body> tag

Comments