I have one little question towards the toggleclass function of the Jquery library. I am currently working on a jquery-mobile app with lists and content articles. Within this articles i want to implement a "nightmode". After touching the nightmode button every article, with the same class but a !!different id!! should toggle its class.
I will show you my article html-structure, my css and my jQuery script for it.
So this is my Code-Structure:
$(document).ready(function(){
$('#nightmode_article1').click(function(){
$('#article1').toggleClass('night');
});
$('#nightmode_article2').click(function(){
$('#article2').toggleClass('night');
});
});
.day {
background-image: url(images/background.jpg);
background-repeat:repeat;
text-align: center;
}
.night {
background-image: url(images/background-night.jpg);
background-repeat:repeat;
text-align: center;
color: #F0F0F0;
text-shadow: none;
}
<div data-role="page" id="article1" class="day">
<header data-role="header">
<button id="nightmode_article1"><img src="images/night-icon.png" /></button>
<h1>Article1</h1>
</header>
<article data-role="content">
</article>
<footer data-role="footer" data-position="fixed">
<nav data-role="navbar">
<ul>
<li><a href="#" data-icon="home">Home</a></li>
<li><a href="#" data-icon="back">Test</a></li>
</ul>
</nav>
</footer>
</div>
<div data-role="page" id="article2" class="day">
<header data-role="header">
<button id="nightmode_article2"><img src="images/night-icon.png" /></button>
<h1>Article1</h1>
</header>
<article data-role="content">
</article>
<footer data-role="footer" data-position="fixed">
<nav data-role="navbar">
<ul>
<li><a href="#" data-icon="home">Home</a></li>
<li><a href="#" data-icon="back">Test</a></li>
</ul>
</nav>
</footer>
</div>
Is there any possibility not to make different buttons for every article? I want to toggle the class in every article (in more then one article id) just by touching/pushing one button with one id.
Is it possible?
Instead of an ID on the night mode buttons, assign all of them the same class, e.g.:
<button class="nightModeButton"><img src="images/night-icon.png" /></button>
Then add a click handler for that class so clicking any of the night mode buttons runs the same code:
$('.nightModeButton').click(function(){
$('[data-role="page"]').toggleClass('night');
});
In the handler, toggle the night class on all articles by using the $('[data-role="page"]')
selector. Assuming all your articles are within the page like your example code, they will all be updated.
If you are dynamically injecting the articles, you will need to save the current mode and set the class for the incoming page.