I have some javascript that is switching between 3 divs on click of 1 of 3 tabs.
Here is my Javascript:
(function($){
$.fn.acidTabs = function(options) {
var settings = {
'style' : 'one'
};
options = $.extend( settings, options );
return this.each (function () {
var o = options;
container = this;
container.setAttribute("class",o.style);
var navitem = container.querySelector("li");
//store which tab we are on
var ident = navitem.id.split("_")[1];
navitem.parentNode.setAttribute("data-current",ident);
//set current tab with class of activetabheader
navitem.setAttribute("class","tabActiveHeader");
//hide two tab contents we don't need
var pages = container.querySelectorAll(".tabpage");
for (var i = 1; i < pages.length; i++) {
pages[i].style.display="none";
}
//this adds click event to tabs
var tabs = container.querySelectorAll("li");
for (var i = 0; i < tabs.length; i++) {
tabs[i].onclick=displayPage;
}
});
// on click of one of tabs
function displayPage() {
var current = this.parentNode.getAttribute("data-current");
//remove class of activetabheader and hide old contents
document.getElementById("tabHeader_" + current).removeAttribute("class");
document.getElementById("tabpage_" + current).style.display="none";
var ident = this.id.split("_")[1];
//add class of activetabheader to new active tab and show contents
this.setAttribute("class","tabActiveHeader");
document.getElementById("tabpage_" + ident).style.display="block";
this.parentNode.setAttribute("data-current",ident);
}
};
})(jQuery);
I cant seem to modifiy this to accept fading effects. Or maybe there is a better way to do this?
Would love your help!
Thank you.
it's not easy because you can't do it.
You need to split the two css statements.
New div with opacity:0 and display:none
change display to block
and then change opacity using setTimeout (even a 10ms delay will do).
do the opposite for the div that will hidden.
something like this:
var newdiv=document.getElementById("tabpage_" + ident);
newdiv.style.display="block";
setTimeout(function(){newdiv.style.opacity="1";},10);
OK figured it out with some help from the asp.net forum. Replace the function displayPage() with this:
var current = this.parentNode.getAttribute("data-current");
//remove class of activetabheader and hide old contents
$('#tabHeader_' + current).removeClass('tabActiveHeader');
$('#tabpage_' + current).hide();
var ident = this.id.split("_")[1];
//add class of activetabheader to new active tab and show contents
$(this).addClass("tabActiveHeader");
$('#tabpage_' + ident).fadeIn();
this.parentNode.setAttribute("data-current",ident);
Related
I'm a little new to Web Development so I was hoping someone could answer this for me.
I'm building a prototype for a "Web Messenger" similar to Facebook messenger. I have a sidebar that I populate with a UL of anchor tags when the window loads and it looks like this. Here is the code for it
var toAdd = document.createDocumentFragment();
var newUL = document.createElement('ul');
newUL.id = 'menu-content';
newUL.className = 'menu-content collapse out';
for(var i = 0; i < 5; i++){
var newLI = document.createElement('li');
var newA = document.createElement('a');
newA.id = 'chat' + i;
newA.setAttribute('href', "#");
newA.innerHTML = "Chat" + (i + 1);
newLI.appendChild(newA);
newUL.appendChild(newLI);
}
toAdd.appendChild(newUL)
document.getElementById("menu-list").appendChild(toAdd);
I also have a Div at the top of the page which will display some details about the current chat, but for the time being will simply display the name of the chat, same as on the anchor tags.
Now based on another StackOverflow post the correct way to call a JS function from an anchor tag is
var c0 = document.getElementById("chat0");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
c0.onclick = function(id) {
//Change Title Name here
//Do other stuff in the future
return false;
}
However I could have 20+ chats on the sidebar at any one time, so this seems like a lot of repetitive code to write.
Is there a better way to do this?
Give your chats a general class instead example chat then attach the click event to all the chat's in the same time using .getElementsByClassName().
So you could add className just after newA.id :
newA.id = 'chat' + i;
newA.className = 'chat';
Then attach the click event :
var chats = document.getElementsByClassName('chat');
for (var i=0; i < chats.length; i++) {
chats[i].addEventListener('click', chatClick, false);
}
function chatClick(){
//chat is clicked
//The 'this' object here refer to clicked element
}
You could use .addEventListener() instead of onclick.
NOTE : You can attach the click event directly after node creation :
for(var i = 0; i < 5; i++){
var newLI = document.createElement('li');
var newA = document.createElement('a');
newA.id = 'chat' + i;
newA.setAttribute('href', "#");
newA.innerHTML = "Chat" + (i + 1);
newA.addEventListener('click', chatClick, false); //Attach click event HERE
newLI.appendChild(newA);
newUL.appendChild(newLI);
}
Hope this help.
Yap sure. You can give them all a class and after load just use a simple jQuery code to bind onclick for all of them:
$('a.className').click(function() {
// Your code here
});
Now if the a tags are added after execution of the code you just simply need to call this again or bind to those elements manually.
so I'm using this code, to slideToggle a box on my webpage.
// OPEN CERTAIN BOX
$(function() {
var sliding = false;
var mq = window.matchMedia( "(min-width: 700px)" );
if (mq.matches) {
var time = 500;
} else {
var time = 0;
}
var id = ('1');
var div = ('#toggle-content-' + id);
var img = ('#toggle-img-' + id);
var toggler = ('toggler-' + id);
$(div).hide()
$(toggler).click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
// ...
As you can see, I'm using the var id, to use the toggle function for a certain box, which has its own css and html code.
I have 7 more boxes. Until now, i copied the code 7 times and changed the id at each copy from 2 - 8. Is there a way to make it with one code?
I tried a for loop, that goes from 1 - 8 but this obviously didnt work.
Has someone an idea? Or do I have to make that 8 copies and changed the id.
Edit:
My approach with the for-loop:
$(function() {
var sliding = false;
var mq = window.matchMedia( "(min-width: 700px)" );
if (mq.matches) {
var time = 500;
} else {
var time = 0;
}
for(i = 1; i <= 8; i++){
var id = (i.toString());
var div = ('#toggle-content-'+id);
var img = ('#toggle-img-'+id);
var toggler = ('toggler-'+id);
$( div ).hide()
$( toggler ).click(function(){
if (sliding == false){
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
...
And this is my html code for one box:
<tr><td cellspacing="0" cellpadding="0" height="50px" class="upper">
<toggler-1><area-head-text><img id="toggle-img-1" src="images/box_opener.png"/>Starterpaket</area-head-text></toggler-1>
</td></tr>
<tr><td>
<div id="toggle-content-1">
<area-head-text>
<img class="text-image" src="images/arrow.png"/>3 individuelle Entwürfe<br>
<img class="text-image" src="images/arrow.png"/>3 Korrekturzeichnungen<br>
<img class="text-image" src="images/arrow.png"/>Internationale Nutzungsrechte<br>
<img class="text-image" src="images/arrow.png"/>400€<br><br>
</area-head-text>
</div>
</td></tr>
I'm not sure why you put "Obviously" a loop doesn't work, because that's pretty much exactly what you should do. Something like this:
for(var i = 1; i <= 8; i++)
{
var div = $('#toggle-content-' + i);
var img = $('#toggle-img-' + i);
var toggler = $('toggler-' + i);
$(div).hide()
$(toggler).click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
// ...
}
This is 2 options.
(and my preference) -
Instead of using an ID to add the click event onto each individual toggle button, use the same class on each, and add the click event on that class. When the user clicks a toggle button traverse the DOM from the clicked toggle button to perform your toggle on the relevant <div>.
This would look something like:
$(function() {
$('.toggleBtn').click(function() {
var sliding = $(this).data('sliding'); //use data attr to store sliding status
if (sliding == false) {
$(this).data('sliding') = true;
}else {
return; //don't toggle we're sliding
}
// navigate to element and toggle
$(this).parent('.someParentElement').children('.theDiv').slideToggle(time,"swing");
//clear sliding status
$(this).data('sliding', false);
}
}
The reason this is my preference, is because although it's faster to target an ID for a click event than a class for a single event, using 7 click events on 7 different IDS in my opinion (I don't know for sure) is less efficient than using a single click event on 1 class. That's my perceived purpose of using events on classes rather than IDS.
Also this way, when you want to add another box in, or remove a box, you don't need to modify any Javascript, the only thing you would need to maintain this code for is if you decide to change the structure of the HTML, and therefore the navigation of the DOM to perform your toggle.
using your method:
var ids = ["id1","id2","id3"];
for(var id in ids) {
var $div = $('#toggle-content-' + id);
var $img = $('#toggle-img-' + id);
var $toggler = $('toggler-' + id);
$div.hide()
$toggler.click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$div.slideToggle(time,"swing");
// ...
}
I have a program that is configured to hide/show table rows when a +/- icon is clicked. The functionality is working, however, I need to figure out a way to reset all hide/show icons when the parent category is toggled closed.
$(function(){
//src vars
var hide_src = "http://www.synchronizeddesigns.com/filter_hide.gif",
reveal_src = "http://www.synchronizeddesigns.com/filter_reveal.gif",
s = '';
//hide all sublevel elements
$(".subsub, .subsubsub").hide();
$("a").click(function(e){
e.preventDefault();
var tID = e.target.id,
tClass = '.' + tID.replace('HS', '');
$(tClass).toggle();
if(!$(tClass).is(':visible')){
s = hide_src;
//for each subcategory
$(tClass).each(function(){
//get class names into classes array
var classes = $(this).attr('class').split(' '),
parentClass = '';
//search classes array for class that begins with 'cat'
for (var j=0; j<classes.length; j++) {
if (classes[j].match("cat")){
parentClass = classes[j];
}
}
//find subsubsub elements that have a class that begins with 'cat#sub'
var subs = $('[class*=' + parentClass + 'sub]');
//if there are sub elements, hide them too
if(subs){
subs.hide();
/*****************************************************
NEED HELP HERE !!!!!!!!!!
Need a way to reset all hide/show images icon
when 'parentClass' hide/show is clicked to close.
*****************************************************/
}
});
} else {
s = reveal_src;
}
//Change image src
$("#" + tID).attr('src', s);
});
});
To replicate: Toggle open all parents and subs, then close one of the parents, then reopen the parent. You'll notice that the +/- icon remains in it's previous state
jsFiddle link
You can find the img nodes for the subcategories under the current one and then change their src attr.
I've updated your jsfiddle: http://jsfiddle.net/nTyWv/12/
The code could be something like:
if(subs){
innerIcons = jQuery.find("a > img[id*="+tID+"sub]");
if (innerIcons) {
$(innerIcons).attr('src', s);
};
subs.hide();
}
I have a search page, and I found a script for a tab component which seperates the TV-Show search page and Movie search page. When a user clicks on lets say the "Movie" tab, and perform a search from there, I make the form add ?type=movie&... to the url. But, when they perform the search, the tab that's selected is the the "TV-Show" tab, and the have to click over to get to the other tab which has the results they want.
Here is the code, and in it is some of what I tried:
the HTML looks like this:
<article class="first">
<h2>Search</h2>
<hr/>
<div id="tabWrapper">
<div id="tabContainer">
<div class="tabs">
<ul>
<li id="tabHeader_1">TV Shows</li>
<li id="tabHeader_2">Movies</li>
</ul>
</div>
<div class="tabContent">
<div class="tabpage" id="tabpage_1">
<?php
if (isset($sortFilt['year']))
unset($sortFilt['year']);
if ($sortField=="year")
$sortField==" ";
DisplaySearchPage("shows", $terms, $sortField, $sortDir, $sortFilt, $page, $perPage);
?>
</div>
<div class="tabpage" id="tabpage_2">
<?php
DisplaySearchPage("movies", $terms, $sortField, $sortDir, $sortFilt, $page, $perPage);
?>
</div>
</div>
</div>
</div>
</article>
<script src="tabs.js"></script>
And this is the the tabs.js script:
window.onload=function() {
// get tab container
var container = document.getElementById("tabContainer");
// set current tab
var navitem = container.querySelector(".tabs ul li");
//store which tab we are on
var ident = navitem.id.split("_")[1];
navitem.parentNode.setAttribute("data-current",ident);
//set current tab with class of activetabheader
navitem.setAttribute("class","tabActiveHeader");
//hide two tab contents we don't need
var pages = container.querySelectorAll(".tabpage");
for (var i = 1; i < pages.length; i++) {
pages[i].style.display="none";
}
//this adds click event to tabs
var tabs = container.querySelectorAll(".tabs ul li");
for (var i = 0; i < tabs.length; i++) {
tabs[i].onclick=displayPage;
}
// This below is is what I tried.
var selTab = (getUrlVars()["type"] == "movies") ? 2 : 1;
var selTab = (getUrlVars()["type"] == "movies") ? 1 : 0; // Tried this too.
tabs[selTab].click();
// its seems like it should have worked, what am I doing wrong.
}
// on click of one of tabs
function displayPage() {
var current = this.parentNode.getAttribute("data-current");
//remove class of activetabheader and hide old contents
document.getElementById("tabHeader_" + current).removeAttribute("class");
document.getElementById("tabpage_" + current).style.display="none";
var ident = this.id.split("_")[1];
//add class of activetabheader to new active tab and show contents
this.setAttribute("class","tabActiveHeader");
document.getElementById("tabpage_" + ident).style.display="block";
this.parentNode.setAttribute("data-current",ident);
}
How can I adapt this script to let me decide which tab is displayed when the page is loaded based on what the type variable is in the URL parameters?
I found the answer. My problem was with getUrlVars["type"], it failed to give me the value of the 'type' url variable, so I created my own function for it. Here is the working code if anyone else is wondering how to get variables from the url.
function getURLParameter(name)
{
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
window.onload = function()
{
// Get tab container
var container = document.getElementById("tabContainer");
// Set the current tab.
var navitem = container.querySelector(".tabs ul li");
// Store which tab is selected.
var ident = navitem.id.split("_")[1];
navitem.parentNode.setAttribute("data-current", ident);
// Set the current tab with a class of 'activetabheader'.
navitem.setAttribute("class", "tabActiveHeader");
// Hide the tab contents we don't need.
var pages = container.querySelectorAll(".tabpage");
for (var i = 1; i < pages.length; i++) {
pages[i].style.display = "none";
}
// This adds the click event handler to the tabs.
var tabs = container.querySelectorAll(".tabs ul li");
for (var i = 0; i < tabs.length; i++) {
tabs[i].onclick = displayPage;
}
// Selects tab based on 'type' url variable.
if (getURLParameter("type") == "movies") {
tabs[1].click();
}
}
// OnClick() event handler for tabs.
function displayPage()
{
var current = this.parentNode.getAttribute("data-current");
// Remove class of 'activetabheader' and hide the old contents.
document.getElementById("tabHeader_" + current).removeAttribute("class");
document.getElementById("tabpage_" + current).style.display = "none";
var ident = this.id.split("_")[1];
// Add a class of 'activetabheader' to new active tab and show contents.
this.setAttribute("class", "tabActiveHeader");
document.getElementById("tabpage_" + ident).style.display = "block";
this.parentNode.setAttribute("data-current", ident);
}
This script creates menu tabs above a text area. The script works if use only once on a page, I however need to use it twice on a single page, to create 2 text areas, each with a menu above them. As soon as I use it twice only one instance works. Any suggestions.
window.onload=function() {
// get tab container
var container = document.getElementById("tabContainer");
// set current tab
var navitem = container.querySelector(".tabs ul li");
//store which tab we are on
var ident = navitem.id.split("_")[1];
navitem.parentNode.setAttribute("data-current",ident);
//set current tab with class of activetabheader
navitem.setAttribute("class","tabActiveHeader");
//hide two tab contents we don't need
var pages = container.querySelectorAll(".tabpage");
for (var i = 1; i < pages.length; i++) {
pages[i].style.display="none";
}
//this adds click event to tabs
var tabs = container.querySelectorAll(".tabs ul li");
for (var i = 0; i < tabs.length; i++) {
tabs[i].onclick=displayPage;
}
}
// on click of one of tabs
function displayPage() {
var current = this.parentNode.getAttribute("data-current");
//remove class of activetabheader and hide old contents
document.getElementById("tabHeader_" + current).removeAttribute("class");
document.getElementById("tabpage_" + current).style.display="none";
var ident = this.id.split("_")[1];
//add class of activetabheader to new active tab and show contents
this.setAttribute("class","tabActiveHeader");
document.getElementById("tabpage_" + ident).style.display="block";
this.parentNode.setAttribute("data-current",ident);
}
Havn't found solution yet, but FYI, you originally marked this as jQuery, if it had been jquery, you could easily break a few lines of that code and write it as simple as: (depending on version)
function displayPage(e) {
var current = $(this).parent().attr("data-current");
$("#tabHeader_" + current).removeClass("tabActiveHeader")
$("#tabpage_" + current).hide();
var ident = this.id.split("_")[1];
$(this).addClass("tabActiveHeader");
$("#tabpage_" + ident).show();
$(this).parent().attr({ 'data-current': ident })
}
$(function() {
var container = $("#tabContainer"),
navitem = container.find((".tabs ul li")).first(),
ident = navitem[0].id.split("_")[1];
navitem.addClass("tabActiveHeader").parent().attr({ 'data-current': ident });
$(".tabpage").filter(function(i) { return i>0; }).hide();
// OR
// $(".tabpage:not(:first-child)").hide();
$(".tabs ul li").on("click", displayPage)
});
See WORKING Example of the previous jQUERY in this jsFiddle
ALSO, Have you look at jQueryUI.Tabs?
Instead of hard-setting window.onload—which replaces the last-set handler with the new one—use the following code that registers an arbitrary number of event handlers for the same event on the same object:
window.addEventListener('load',function(){
// Your code here
},false);
More can be read about element.addEventListener and specifically IE Support
This will not work for older versions of IE; if you need this support, I strongly recommend using a cross-browser library like jQuery. You originally tagged your question as relating to jQuery, but there is no jQuery used in your code.