An assignment I have is to make a FAQ page for a website that displays an answer when you click on a question and also only allows one question to be visible at a time. I did this so far:
<li button onclick="answerOne();">question</li>
<span id="FAQA1" style="visibility: hidden; color: red;">answer</span>
<li button onclick="answerTwo();">question</li>
<span id="FAQA2" style="visibility: hidden; color: red;">answer</span>
<li button onclick="answerThree();">question</li>
<span id="FAQA3" style="visibility: hidden; color: red;">answer</span>
And my Javascript looks like this:
function answerOne() {
document.getElementById("FAQA1").style.visibility = "visible";
document.getElementById("FAQA2").style.visibility = "hidden";
document.getElementById("FAQA3").style.visibility = "hidden";
}
function answerTwo() {
document.getElementById("FAQA1").style.visibility = "hidden";
document.getElementById("FAQA2").style.visibility = "visible";
document.getElementById("FAQA3").style.visibility = "hidden";
}
function answerThree() {
document.getElementById("FAQA1").style.visibility = "hidden";
document.getElementById("FAQA2").style.visibility = "hidden";
document.getElementById("FAQA3").style.visibility = "visible";
}
Now this is all well and good but if the page ever gets bigger, you'd have to change every single function. I know there must be a better way to be able to achieve the same result but I seem to have hit a wall. If anyone knows a way to do this, can you point me in the right direction or to a source where I can find it? Many thanks.
You could try something like this:
var current = false;
function makeActive( key ) {
if( current !== false ) {
document.getElementById( "FAQ" + current ).style.visibility = "hidden";
}
document.getElementById( "FAQ" + key ).style.visibility = "visible";
current = key;
}
calling makeActive( "A1" ); would make FAQ item "A1" be visible and the previously active one become invisible
There's a number of ways you can do this. Here's one that doesn't involve so many functions.
Set up your HTML like this:
<li onclick="showAnswer('FAQA1')">question</li>
<span id="FAQA1" class="answer" style="visibility: hidden; color: red;">answer</span>
<li onclick="showAnswer('FAQA2')">question</li>
<span id="FAQA2" class="answer" style="visibility: hidden; color: red;">answer</span>
<li onclick="showAnswer('FAQA3')">question</li>
<span id="FAQA3" class="answer" style="visibility: hidden; color: red;">answer</span>
Notice that all the li elements use the same function and simply pass a string to it. The answer spans all have the same class and a unique id.
Then the Javascript:
function showAnswer(ele) {
[].forEach.call(document.querySelectorAll('.answer'), function(el) {
el.style.visibility = 'hidden';
});
document.getElementById(ele).style.visibility = 'visible';
}
So here, there's a forEach loop on all the elements with class answer (the answer spans). This loops through all the answers and hides them. Then, the last line selects the element with a particular id (that we've passed into the function as a string from the onclick) and sets that answer visible.
A fiddle: https://jsfiddle.net/dsmw0abe/2/
Also, just FYI, keep in mind that visibility is different from display.
You could create a function that allows you to have an unlimited number of questions. By giving every answer span the same class, you do not have to explicitly define each one in your code.
Because your answers start at 1, I am starting the loop at 1 instead of 0.
Example:
window.answerQuestion = function answerQuestion(id) {
var questionEls = document.getElementsByClassName("answer");
for (var x = 1; x <= questionEls.length; x++) {
var question = questionEls[x-1];
if (x === id) {
question.style.visibility = 'visible';
} else {
question.style.visibility = ' hidden';
}
}
};
Demo:
https://jsfiddle.net/j3k89o5a/
One approach is to to start w/ all answers hidden then listen for an event within the div at which time you can capture which item was clicked and toggle visibility of nearest following answer. If it is clicked again, it will toggle that answer closed. This allows the user to open each question as they see fit and prevents the page from jumping around - i.e. closing previous answer when a new question is clicked.
For Example
HTML
<div class="faq">
<h1>First Question</h1>
<p>Answer to the question</p>
<h1>Second Question</h1>
<p>Answer to the question</p>
<h1>Third Question</h1>
<p>Answer to the question</p>
</div>
CSS
.faq {
display: none
}
Javascript/jQuery (could be done w/ vanilla js, if needed)
$(function() {
$('.faq h1').click(function() {
$(this).next('p').slideToggle(400);
});
});
Related
I would like to create a curriculum presentation by Java Script similar to the one on Udemy.
https://prnt.sc/22zxxrp
I have tried to put both button and content in the same div and to add an event listener which would on click trigger conditional check if both of the elements are of the same parent and if true to display the content.
But it does not work.
The code would be something like this but with more buttons.
let batonceros = document.getElementsByClassName("batno");
let paragraph = document.getElementsByClassName("para");
batonceros.addEventListener("click", function() {
if( batonceros != paragraph && batonceros.parentNode == paragraph.parentNode) {
batonceros.style.display = "block";
}
else {
batonceros.style.display = "none";
}
});
Not exactly sure what you're trying to accomplish, but maybe this might help. It shows how to reference the parent container to find the relative .para from its .batno
let batonceros = document.querySelectorAll(".batno");
let paragraph = document.querySelectorAll(".para");
batonceros.forEach(button => button.addEventListener("click", e => {
e.target.closest('div').querySelector('.para').classList.toggle('show');
}));
.para {
display: none;
}
.show {
display: block;
}
<div>
<p class='para'>This is a paragraph</p>
<button class='batno'>Button</button>
</div>
<div>
<p class='para'>This is a paragraph</p>
<button class='batno'>Button</button>
</div>
To debug, try to see if it works without checking the parent. Also, no need to check to see if the button equals the paragraph. Also, you are changing the button style, not the paragraph style.
batonceros.addEventListener("click", function() {
paragraph.style.display = "block";
}
If this does cause the paragraph to display, your problem may in your element structure.
I'm trying to make a menu (with buttons) that open links.
when you hover on the buttons, a slideDown reveals more information on that link.
I've gotten all those features to technically work, however i can't get the animation speed to go any slower than instantly.
I'm really new to javascript and Jquery, and it took me 2-3 days to get the javascript and CSS to do what i have so far... and yeah it's probably bloated... but i'm still proud i got this done so far :D
PS, I know most menus are made w/ul's but I really like the way the buttons look and detested trying to put the list together. last time i tried used a seperate ul for the information and it kept styling the second list like the first because it was inside it... so annoying. I also tried vertical-link list w/CSS but still think flat 'buttons' are so boring. i really like the 3D esk of the actual html
HTML:
<div class="mainmenu">
<div id="homemenu">
<button id="home" class="mmbutton active">Home</button>
<div id="homesub" class="sub active">-just a bit about this page</div>
</div>
<div id="photosmenu">
<button id="photos" class="mmbutton">Photos</button>
<div id="photossub" class="sub inactive">-just a bit about this page
</div>
</div>
</div>
javascript/jquery:
$(function(){
var mmbutton = $('.mmbutton');
var start = "http://";
var address = "[my web address"; //add "http:
var about = "[web address]/aboutme.html";
var id = 0;
var rel = 0;
var mmsub = 0;
//<click link buttons:
$(mmbutton).click(function(){
var id = $(this).attr('id');
if (id === "home") {
location.replace(start+address);
}else if (id === "about") {
window.alert("I'm sorry I don't have this page set up yet. Thank you for visiting my page!");
//add additional buttons here under 'else if' unless its a subdomain
}else {
location.replace(start+id+'.'+address);//goes to any subdomain by id
}});
//>detect hover
$(mmbutton).hover(function(){
id = $(this).attr('id');
rel = '#'+id+'sub';
mmsub = '#'+id+'menu';
console.log('mouseenter'+rel);
$(rel).removeClass('inactive');
$(rel).stop().slideDown(500000);
}, function(){
console.log('mouseleave'+rel);
$(rel).addClass('inactive');
if ( $(this).hasClass('active')) {
$(rel).removeClass('inactive');
console.log('this is active');
}if ($(rel).hasClass('inactive')){
$(rel).stop().slideUp(500000);
}});});
relevante CSS:
.inactive {
display: none;
}
.sub {
transition-duration: 1s;
}
You can do it setting all that info divs to display:none and use slideToggle() function for that. Considering you want to keep the subdiv's opened when you're over them, one option is create a span element that include the button and the subdiv, and apply the hover to that span. So...
HTML:
<div class="mainmenu">
<div id="homemenu">
<span class="subcontainer">
<button id="home" class="mmbutton active">Home</button>
<div id="homesub" class="sub">-just a bit about this page</div>
</span>
</div>
<div id="photosmenu">
<span class="subcontainer">
<button id="photos" class="mmbutton">Photos</button>
<div id="photossub" class="sub">-just a bit about this page</div>
</span>
</div>
</div>
CSS:
.sub {
display: none;
/*transition-duration: 1s; IMPORTANT: REMOVE THIS!!*/
}
JQUERY:
$('span.subcontainer').hover(function() {
$(this).find('div.sub').slideToggle('slow');
});
IMPORTANT: Check that to make it work you have to remove the transition style you've created for .sub divs (it interfeers with the jquery function).
NOTE: I don't use the div.homemenu or div.photosmenu as the containers for the hover because div's normally have some styles pre-applied by default and can interfeer with the desired behaviour (for example, they normally have width=100% so the hover applies even when you're outside of the button or subdiv in the same line). span is normally more innocuous to use it just as a wrapper.
I hope it helps
Oh! i got it. i was trying to do too much (show off.../ using what im learning).
I removed the line that added and removed the class 'inactive' and just toggled the SlideUp and slideDown when i wanted it too. now i can adjust the animation speed:
(HTML remains unchanged)
CSS: removed the "transition-duration: 1s;"
JavaScript:
$(function(){
var mmbutton = $('.mmbutton');//any/all buttons
var activebut= 0; //detect button classes
var mmdiv = $("div[id$='menu']");//detect button sub info
var start = "http://";
var address = "[address]/index.html"; //add "http://" + [blog or games] + address
var about = "http://[address]/aboutme.html";
var id = 0;
var sub = 0;
var slidespeed= 450; //slideUP/slideDown animation speed //added var for speed
//<click link buttons: (unchanged)
$(mmbutton).click(function(){
id = $(this).attr('id');
if (id === "home") {
location.replace(start+address);
}else if (id === "about") {
location.replace(start+'[address]/aboutme/index.html')
//add additional buttons here under 'else if' unless its a subdomain
}else {
location.replace(start+id+'.'+address);//goes to any subdomain by id
}
});
//<hover display:
//<detect mouse ON button
$(mmbutton).hover(function(){
id = $(this).attr('id');
sub = '#'+id+'sub';
activebut= $(this);
if ( $(activebut).hasClass('active')) {
}else {
$(sub).stop().slideDown(slidespeed);
}
});
//<detect mouse off button AND div
$(mmdiv).mouseleave(function(){
if ( $(activebut).hasClass('active')) {
}else {
$(sub).stop().slideUp(slidespeed);
}
});
});
I am trying to toggle a div when its name is clicked.
I have multiple coupls like that in my page, and I want it to work as
"when <p id= "d2"> is clicked => <div id="d2"> is toggled".
I tried those functions:
$(document).ready(function(){
$("p").click(function(){
$("div#" + $(this).attr('id')).toggle();
});
});
function rgt() {
//document.body.innerHTML = "";
var id = "d" + this.id;
var situation = document.getElementById(id).style.display;
if (situation == "none") {
situation = "block";
}
else {
situation = "none";
}
}
function showHide(theId) {
if (document.getElementById("d" + theId).style.display == "none") {
document.getElementById("d" + theId).style.display = "block";
}
else {
document.getElementById("d" + theId).style.display = "none";
}
}
I can't make it Work!!! Why is it?
the browser says:"no 'display' property for null"...
I will be more than happy to solve it with simple jquery
Ensure Your id Attributes Are Unique
Assuming that your id attributes are unique, which they are required to be per the specification:
The id attribute specifies its element's unique identifier (ID). The
value must be unique amongst all the IDs in the element's home subtree
and must contain at least one character. The value must not contain
any space characters.
You should consider renaming your id attributes to d{n} and your paragraphs to p{n} respectively as seen below :
<button id='p1'>p1</button> <button id='p2'>p2</button> <button id='p3'>p3</button>
<div id='d1'><pre>d1</pre></div>
<div id='d2'><pre>d2</pre></div>
<div id='d3'><pre>d3</pre></div>
which would allow you to use the following function to handle your toggle operations :
$(function(){
// When an ID that starts with P is clicked
$('[id^="p"]').click(function(){
// Get the proper number for it
var id = parseInt($(this).attr('id').replace(/\D/g,''));
// Now that you have the ID, use it to toggle the appropriate <div>
$('#d' + id).toggle();
})
});
Example Using Unique IDs
You can see an interactive example of this approach here and demonstrated below :
Consider Using data-* Attributes
HTML supports the use of data attributes that can be useful for targeting specific elements through jQuery and associating them to other actions. For instance, if you create an attribute on each of your "p" elements as follows :
<button data-toggles='d1'>p1</button>
<button data-toggles='d2'>p2</button>
<button data-toggles='d3'>p3</button>
and then simply change your jQuery to use those as selectors :
$(function(){
// When an element with a "toggles" attribute is clicked
$('[data-toggles]').click(function(){
// Then toggle its target
$('#' + $(this).data('toggles')).toggle();
});
});
Is this you are looking?
$("#p1").on("click", function() {
$("#d1").toggle();
});
js fiddle: https://jsfiddle.net/Jomet/09yehw9y/
jQuery(function($){
var $toggles = $('.divToggle');
var $togglables = $('.togglableDiv');
$toggles.on('click', function(){
//get the div at the same index as the p, and toggle it
$togglables.eq($toggles.index(this)).toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="divToggle">Show Me 1</p>
<p class="divToggle">Show Me 2</p>
<p class="divToggle">Show Me 3</p>
<div class="togglableDiv">Weeee 1</div>
<div class="togglableDiv">Weeee 2</div>
<div class="togglableDiv">Weeee 3</div>
Minimal approach using classes. This solution assumes the order of the p elements in the dom are in the same order as the divs are in the order. They do not have to be contiguous, but the order does matter with this solution.
ids are not the droids you are looking for.
An id needs to be unique. If you want to classify something one would suggest to use classes. You can actually use serveral of them for some fancy stuff. How about something like this:
<p class="toggle one">one</p>
<div class="toggle one" style="display:none">content one</div>
Straight forward. Every element that is a switch or switchable gets the class toggle. Each pair of switch and switchable(s) gets an additional identifier (like one, two, ...).
Simple JScript Implementation:
Now how about not using JQuery to work with that? Sure it i$ handy, but it hides all that neat stuff one would eventually like to learn her/himself!
var myToggle = {};
(function(module) {
"use strict";
(function init() {
var elements = document.getElementsByClassName("toggle");
var element;
var i = elements.length;
while (i) {
i -= 1;
element = elements[i].className;
elements[i].setAttribute("onclick", "myToggle.swap(\"" + element + "\")");
}
}());
module.swap = function(element) {
var couple = document.getElementsByClassName(element);
var i = couple.length;
while (i) {
i -= 1;
if (couple[i].style.display === "none" && couple[i].tagName === "DIV") {
couple[i].style.display = "block";
} else if (couple[i].tagName === "DIV") {
couple[i].style.display = "none";
}
}
};
}(myToggle));
<p class="toggle one">one</p>
<div class="toggle one" style="display:none">content one</div>
<p class="toggle two">two</p>
<div class="toggle two" style="display:none">content two 1</div>
<div class="toggle two" style="display:none">content two 2</div>
var myToggle = {} is the object we use to keep our little program contained. It prevents that our code conflicts with other declarations. Because what if some plugin on our site already declared a function called swap()? One would overwrite the other!
Using an object like this ensures that our version is now known as myToggle.swap()!
It may be hard to follow how it got to that name. Important hint: something looking like this... (function() { CODE } ()) ...is called an immediately-invoked function expression. iffy! It's a function that is immediatly executed and keeps its variables to itself. Or can give them to whatever you feed it in the last ()-pair.
Everything else is as verbose as can be... no fancy regular expressions, hacks or libraries. Get into it!
I am trying to make webpage where there is a div in the center which is being changed, instead of going to different pages.
Ultimately, I would like to have the new div, when clicking on an arrow, to flow from right or left in to the center. But first I would like to make the divs appear and disappear when clicking on the arrows but unfortunately this doesn't work.
This is my javascript:
<script>
function changeToHome() {
document.getElementById("mainmain").style.display="block";
document.getElementById("mainmain2").style.display="none";
document.getElementById("mainmain3").style.display="none";
document.getElementById("mainmain4").style.display="none";
}
function changeToStudy() {
document.getElementById("mainmain").style.display="none";
document.getElementById("mainmain2").style.display="block";
document.getElementById("mainmain3").style.display="none";
document.getElementById("mainmain4").style.display="none";
}
function changeToJob() {
document.getElementById("mainmain").style.display="none";
document.getElementById("mainmain2").style.display="none";
document.getElementById("mainmain3").style.display="block";
document.getElementById("mainmain4").style.display="none";
}
function changeToContact() {
document.getElementById("mainmain").style.display="none";
document.getElementById("mainmain2").style.display="none";
document.getElementById("mainmain3").style.display="none";
document.getElementById("mainmain4").style.display="block";
}
function changePageRight() {
var displayValue5 = document.getElementById('mainmain').style.display;
var displayValue5 = document.getElementById('mainmain2').style.display;
var displayValue6 = document.getElementById('mainmain3').style.display;
var displayValue7 = document.getElementById('mainmain4').style.display;
if (document.getElementById('mainmain').style.display == "block") {
document.getElementById("mainmain").style.display="none";
document.getElementById("mainmain2").style.display="block";
}
else if (document.getElementById('mainmain2').style.display == "block") {
document.getElementById("mainmain2").style.display="none";
document.getElementById("mainmain3").style.display="block";
}
else if (document.getElementById('mainmain3').style.display == "block") {
document.getElementById("mainmain3").style.display="none";
document.getElementById("mainmain4").style.display="block";
}
else if (displayValue8 == block) {}
}
function changePageLeft() {
var displayValue = document.getElementById('mainmain').style.display;
var displayValue2 = document.getElementById('mainmain2').style.display;
var displayValue3 = document.getElementById('mainmain3').style.display;
var displayValue4 = document.getElementById('mainmain4').style.display;
if (displayValue == "block") { }
else if (displayValue2 == "block") {
document.getElementById("mainmain").style.display="block";
document.getElementById("mainmain2").style.display="none";
}
else if (displayValue3 == "block") {
document.getElementById("mainmain2").style.display="block";
document.getElementById("mainmain3").style.display="none";
}
else if (displayValue4 === "block") {
document.getElementById("mainmain3").style.display="block";
document.getElementById("mainmain4").style.display="none";
}
}
</script>
Now I have a few divs that look like this:
<div id="mainmain4">
<img style="width:400px;height:327px;margin-left:auto;margin-right:auto;display:block;" src="Untitled-22.png" />
<h2> My name </h2>
<p>Hi,</p>
<p>Some text</p>
</div>
With these css atributes:
#mainmain {
float: left;
width: 575px;
display: block;
position: relative;
}
And all other divs with display: none; so I can change this to block and the one that was block to none.
For some reason, after when I click on one button of the menu, which activates a changeToX() function, the arrows work great. But before that, when you first go to the website, it doesn't.
Can someone explain me what I do wrong?
You don't tell the browser which divs shall be displayed on load. You can use theonloadevent for this:
<body onload="changeToHome()">
One additional hint: you maybe don't want to use inline JavaScript and CSS.
jQuery is as this simple:
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
toggle!
<div id="mainmain">test text</div>
<script>
// you need this, only apply javascript when all html (dom) is loaded:
$(document).ready(function() {
$('.toggle-container').on('click', function(e) {
e.preventDefault(); // this prevents the real href to '#'
// .toggle() is like "on / off" switch for hiding and showing a container
$($(this).data('container')).toggle();
});
});
</script>
This function can be reused, because it is based on classes instead of id's.
Check this JSFiddle: http://jsfiddle.net/r8L6xg15/
Maybe this is of some use. I've tried to make a page control-like behaviour. You can select any container div and put elements in there that have the class 'page'. The JavaScript code will let you navigate those with buttons.
You can make it more fancy by adding the buttons through JavaScript. What you then have is basically a list of pages which are normally displayed as regular divs, but when the script kicks in, it changes them to a page control.
You can call this for any parent element, and in that sense it behaves a bit like a jQuery plugin. It is all native JavaScript, though. And not too much code, I hope. Like you said, I think it's good to learn JavaScript at first. It is very powerful by itself, and it's becoming increasingly powerful. jQuery adds a lot of convenience functions and provides fallbacks in case browser don't support certain features, or when implementations differ. But for many tasks, bare JavaScript will do just fine, and it certainly can't hurt to know your way around it.
Press the 'Run this snippet' button at the bottom to see it in action.
function Pages(element)
{
// Some initialization
var activePage;
// Find all pages within this element.
var pages = document.querySelectorAll('.page');
var maxPage = pages.length - 1;
// Function to toggle the active page.
var setPage = function(index)
{
activePage = index;
for (p = 0; p <= maxPage; p++)
{
if (p == activePage)
pages[p].className = 'page active';
else
pages[p].className = 'page inactive';
}
}
// Select the first page by default.
setPage(0);
// Handler for 'previous'
element.querySelector('.prev').onclick = function()
{
if (activePage == 0)
return;
setPage(activePage - 1);
}
// Handler for 'next'
element.querySelector('.next').onclick = function()
{
if (activePage == maxPage)
return;
setPage(activePage + 1);
}
// Add a class to the element itself. This way, you can already change CSS styling
// depending on whether this code is loaded or not. So in case of an error, the
// divs are just all show underneath each other, and the nav buttons are hidden.
element.className = element.className + ' js';
}
Pages(document.querySelector('.pages'));
.pages .page {
display: block;
padding: 40px;
border: 1px solid blue;
}
.pages .page.inactive {
display: none;
}
.pages .nav {
display: none;
}
.pages.js .nav {
display: inline-block;
}
<div class="pages">
<button class="nav prev">Last</button>
<button class="nav next">Next</button>
<div class="page">Page 1 - Introduction and other blah</div>
<div class="page">Page 2 - Who am I? Who are you? Who is Dr Who?</div>
<div class="page">Page 3 - Overview of our products
<ul><li>Foo</li><li>Bar</li><li>Bar Pro</li></ul>
</div>
<div class="page">Page 4 - FAQ</div>
<div class="page">Page 5 - Contact information</div>
</div>
To dos to make this a little more professional:
Add the navigation through JavaScript
Disable the buttons when first/last page has been reached
Support navigation by keys too (or even swipe!)
Some CSS transform (fade or moving) when toggling between pages
Smarter adding and removing of classes. Now I just set className, which sucks if someone would like to add classes themselves. jQuery has addClass and removeClass for this, which is helpful. there are also stand-alone libraries that help you with this.
Visible indication of pages, maybe with tabs at the top?
I'm trying to create notifications system in my company's ERP, similar to Facebook one. For now, after few hours of work, it looks like this:
Each menu item is a lielement. Each element can have one of classes that will modify it's background color:
selected is blue, shown on a picture
restricted is red
Now, what I'm trying to achieve is to make li background blink on some events (when new message comes in and list is not opened (and also selectedclass is not present)).
The problem is: it won't blink. :(
here's snap of my html (excluding messagebox)
<li class="notifications-topmenu-button selected">
<a href="#">
<div class="notifications-topmenu-button-wrapper">
<div class="notifications-topmenu-button-icon">
<img class="transparent" width="13" height="13" align="absmiddle" src="/images/icons/notifications.png" title="Powiadomienia" alt="Powiadomienia">
</div>
<div class="notifications-topmenu-button-counter" style="display: block;">3</div>
</div>
</a>
<span class="divider"> : </span>
</li>
<li class="selected">
Strona główna
<span class="divider"> : </span>
</li>
Also, there's some JavaScript initiating object (don't mind comments):
function notificationsObject(){
var nl = new Object();
//atrybuty klasy
nl.liElement = $('.notifications-topmenu-button');
nl.menuButton = $('.notifications-topmenu-button-wrapper');
nl.menuButtonCounter = nl.menuButton.find('.notifications-topmenu-button-counter');
nl.notificationsCount = jQuery.trim(nl.menuButtonCounter.text());
nl.notificationsList = $('.notifications-list-wrapper');
nl.blinkingInterval = null;
nl.startBlinking = function(){
nl.blinkingInterval = setInterval(function(){
if(nl.liElement.hasClass('restricted') == false){
console.debug(nl.liElement.addClass('restricted'));
}
else {
nl.liElement.removeClass('restricted');
}
}, 1000);
}
nl.stopBlinking = function(){
if(nl.blinkingInterval != null) nl.blinkingInterval = null;
}
(more 'class' functions)
return nl;
}
Now to test it, I simply call
$(document).ready(function(){
var notifications = notificationsObject();
notifications.startBlinking();
});
Of course I call it after function declaration.
funny fact is that when I change nl.startBlinking function setInterval internals to only add restrictedclass, it works. I'm pretty sure it must be some typo or stupid error, but I can't find it.
Please, help!
Try to use the toggleClass function instead of checking classes yourself like:
setInterval(function(){
nl.liElement.toggleClass('restricted');
}, 1000);
jQuery reference: http://api.jquery.com/toggleClass/
I put all your code into a Fiddle here and it worked. Not sure what the problem is.
added css
.restricted{
visibility:hidden;
}
Also removed (more 'class' functions) line. But I assume you just added that to the post and it's not part of your code.
Ok, problem solved.
the thing was that this function
nl.startBlinking = function(){
nl.blinkingInterval = setInterval(function(){
if(nl.liElement.hasClass('restricted') == false){
console.debug(nl.liElement.addClass('restricted'));
}
else {
nl.liElement.removeClass('restricted');
}
}, 1000);
}
started executing on declaration.
so when I called
$(document).ready(function(){
var notifications = notificationsObject();
notifications.startBlinking();
});
I had not one, but two intervals working at the same time.
Add and remove the 2 classes in stead of only restricted
if(nl.liElement.hasClass('restricted') == false){
nl.liElement.addClass('restricted');
nl.liElement.removeClass('selected');
}
else {
nl.liElement.removeClass('restricted');
nl.liElement.addClass('selected');
}