jquery tabs have to click twice to show div - javascript

I have this jquery code:
$(document).ready(function() {
$(".tabLink").each(function(){
if(location.hash) {
$(".tabLink").removeClass("activeLink");
$(location.hash+"-1").addClass("activeLink");
$(".tabcontent").addClass("hide")
$(location.hash+"-1").removeClass("hide")
} else {
$(".tablink").click(function(){
$(".tabLink").removeClass("activeLink");
$(this).addClass("activeLink");
$(".tabcontent").addClass("hide")
$(location.hash+"-1").removeClass("hide")
});
}
});
});
to switch between tabs, my html is:
Company
Contacts
<div class="tabcontent" id="companyinfo-1">
</div>
<div class="tabcontent" id="contacts-1">
</div>
when i choose another tab i have to click it twice to make the div show
here is a fiddle with the full code : http://jsfiddle.net/2SRZE/

FIDDLE
Why not keep it simple and grab the target right off the anchor link instead of the page URL?
<div class="tab-box">
Company
Contacts
</div>
<div class="tabcontent" id="companyinfo-1">
Tab 1 Content
</div>
<div class="tabcontent hide" id="contacts-1">
Tab 2 Content
</div>
$(document).ready(function() {
if(location.hash) {
// maybe do a little more validation here
setActiveLink(location.hash);
}
$('.tabLink').click(function(e) {
e.preventDefault();
var target = $(this).attr('href');
document.location.hash = target;
setActiveLink(target);
});
function setActiveLink(target) {
$(".tabLink").removeClass("activeLink");
$('a[href=' + target + ']').addClass("activeLink");
$('.tabcontent').addClass('hide');
$(target).removeClass('hide');
}
});

A comment on why you have to click twice:
When you click the tab and the event is triggered the address of the window still has not changed. On first click that would mean no hash. On subsequent clicks that would mean the hash has the value of previous clicked anchor.
Page enter: hash == ''
Click on Contacts: hash == ''
Hide content. (Company is being hided.)
Show hash + '-1' (no match as hash is empty.)
Event done, window hash changes: hash == '#contacts'
Click on #contacts: hash == '#contacts'
Hide content. (Nothing to hide).
Show hash + '-1': contacts-1 show.
Easier by example. Here the text-box is updated with hash value on each click.
Fiddle
As you can see, the hash changes too late.
So: As noted by Lucky Soni, check the target event's href value.

http://jsfiddle.net/awesome/svP3T/2/
$(document).ready(function () {
$(".tabcontent").addClass("hide");
$($(".activeLink").attr('href') + '-1').removeClass("hide");
$(".tabLink").each(function () {
var _tabLink = $(this);
var _tabLinkAttr = $(_tabLink.attr('href') + '-1');
_tabLink.click(function () {
$(".tabLink").removeClass("activeLink");
_tabLink.addClass("activeLink");
$(".tabcontent").addClass("hide");
_tabLinkAttr.removeClass("hide");
});
});
});

check this out: http://jsfiddle.net/awesome/svP3T/4/
see this too: $(window) bind hashchange how to check part hash changed?
var originalHash = window.location.hash;
$(document).ready(function () {
$(window).bind('hashchange', function () {
// remove all active
$(".tabLink").removeClass("activeLink");
$(".tabcontent").addClass("hide");
// https://stackoverflow.com/questions/7699073/window-bind-hashchange-how-to-check-part-hash-changed
var newHash = window.location.hash;
var _origHash = originalHash;
originalHash = newHash;
// log
console.log('original: ' + _origHash);
console.log('new: ' + newHash);
// update active
$('[href="' + newHash + '"]').addClass("activeLink");
$(newHash + '-1').removeClass("hide");
});
// init
$(".tabcontent").addClass("hide");
$($(".activeLink").attr('href') + '-1').removeClass("hide");
});

Related

Onload bootstrap tab trigger

The active class isn't working and I've tried body On-load click trigger and obviously show tab using id and many other ways, however nothing seems to be working. I have hashed the URL to enable tabs to be linked individually in the search. Any help is much appreciated.
JS: to hash the URL and jump to tab
// jump to tab if it exists
if (location.hash) {
$('a[href=' + location.hash + ']').tab('show');
}
// add tab hash to url to persist state
$(document.body).on("shown.bs.tab", function(e){
location.hash = e.target.hash;
});
});
JS: To go to tab home (not working)
$("document").ready(function(){
$("#home").trigger("click");
});
HTML:
<div class="col-xs-5 col-md-2 nopadding">
<nav class="nav-sidebar">
<ul class="nav tabs">
<li class="lead3">Home </li>
<li class="lead3">tab1</li>
<li class="lead3"><a href="#tab3" data-toggle="tab" >tab3</a></li>
<li class="lead3"> Contact </li>
</ul>
</nav>
tab-pane:
<div class="tab-pane active fade text-style" id="home"> . .. </div>
What you expect from this line?
$("home").trigger("click");
I suppose Jquery can't find element here $("home"). You could evaluate it in console for check.
if you are going to find element with class 'home' or id 'home' then you should use $(".home") or $("#home") properly.
It looks like your Document Ready event doesn't work.
Try remove the quotes around the $("document").
A shorter method for this event is as follows:
$(function() {
});
I know that this is very late but I'd like to post my solution since this was something that I was stuck on as well. There's an important subtlety that I think is easy to miss. You want to trigger the click on the <a> tag inside the nav, not the actual panel. Remember you click on the tab not on the panel to trigger it into view. So to get the correct tab to show when the user navigates to /my/path#home you want to bind on the hashchange event and click the correct element. See https://stackoverflow.com/a/680865/5262119 for more info on binding to the hashchange event.
$(window).bind('hashchange', function(event){
var hash = window.location.hash;
// get the actual anchor tag that links to the panel
var $matchingAnchor = $('nav a[href^="' + hash + '"');
if ($matchingAnchor) $matchingAnchor.click();
});
And assuming you want to restrict this to trigger only a certain page then you can add a location check:
$(window).bind('hashchange', function(event){
var path = window.location.pathname;
var hash = window.location.hash;
var $matchingAnchor = $('nav a[href^="' + hash + '"');
var contextRegex = /my\/page/;
var correctPage = contextRegex.test(path);
if (correctPage && $matchingAnchor) $matchingAnchor.click();
});
I imagine you also want to make sure that clicks on the tabs update the hash in the URL window so bind to the tabs event:
$('nav a').on('click',function() {
var $a = $(this);
var hash = $a.attr("href");
window.location.hash = hash;
});
This would go inside your ready function. You will also have to make sure that the function that triggers the click happens when the page first loads.
Complete solution:
$(document).ready(function() {
// Declare clickback function
function triggerTabClick() {
var path = window.location.pathname;
var hash = window.location.hash;
var $matchingAnchor = $('nav a[href^="' + hash + '"');
var contextRegex = /my\/page/; // or whatever you want this to be
var correctPage = contextRegex.test(path);
if (correctPage && $matchingAnchor) $matchingAnchor.click();
}
// Trigger it when the hash changes
$(window).bind('hashchange', triggerTabClick);
// Trigger it when the page loads
triggerTabClick();
// Hook into click for tabs to make sure hash is updated on click
$('nav a').on('click',function(event){
event.preventDefault();
var $a = $(this);
var hash = $a.attr("href");
var window.location.hash = hash;
})
})

Not able to load html within div more than once

I have a listener for tab selection changes, and want to be able to load content in a div element, everytime I click on a tab:
However, the following works only for the first time. With subsequent clicks on the tabs, the page (or div region) is blank.
tabSelectionHandler = function (event, ui) {
// .... code to get tab that was clicked
//..code to get URL
var nextURL = PAGE_URL[tabName];
$('#' + tabName + 'Content').load(nextURL, function (responseTxt, statusTxt, xhr) {});
}
I want the content to be loaded everytime tab is clicked, as the content may be dynamic.. How do I do that?
How I do this is like this:
Suppose I have the following HTML:
<div id="tabs">
<ul>
<li>abc</li>
<li>xyz</li>
</ul>
<div id="tabs-1"></div>
<div id="tabs-2"></div>
</div>
Then you can access each tab like this:
$('#tabs').tabs({
activate: function (event, ui) {
var active = $("#tabs").tabs("option", "active");
var tabId = $("#tabs ul>li a").eq(active).attr('href');
if (tabId === "#tabs-1") {
//set url here
loadHtml(tabId,url );
} else if (tabId === "#tabs-2") {
//set url here
loadHtml(tabId,url );
}
}
});
And then have a javaScript function that loads the content:
function loadHtml(id,url){
$('#'+id).html("some html here");
//you can place an ajax call here or whatever is suitable
//In your case that would be something like
//$('#' + id).load(url);
}
Hope that helps

Open page based on $(this) selector

I'm modifying a wordpress site and have a menu with four anchor tags (buttons) to the left of a slider. When a user selects a button, the slide associated with the button shows. Now, I'd like to open a page when the user clicks the button, instead of showing the slide. Here is the code so far:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$a = $(this);
$(this).showSlide();
if($a.id == $('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Here I'm testing to see if I can click on the anchor with the id '#slide-1285' and log it to the console. It always says 'not testing'. I'm going to set up conditions for all id's so a user is redirected to the correct page. Something like this:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$(this).showSlide();
if($a.id == $('#slide-1285')){
window.location.href = "http://webpage1";
}
elseif($a.id == $('#slide-1286')){
window.location.href = "http://webpage2";
}
elseif($a.id == $('#slide-1287')){
window.location.href = "http://webpage3";
}
else($a.id == $('#slide-1288')){
window.location.href = "http://webpage4";
}
});
Any ideas? Thanks in advance.
To get the id of the element that was clicked, you can do:
$(this).attr('id');
That will return a string. So you could do:
if($(this).attr('id') === 'slide-1285') { do something }
$('#slide-1285') would return a jquery element, but you want just the id. I think the code above is more what you are looking for.
You can add a new data attribute to each of your link and then get that value and redirect.
<a data-webpage="http://webpage1" href="whatever" id="slide-123"></a>
<a data-webpage="http://webpage2" href="whatever" id="slide-456"></a>
.....
and then
// this will bind all ids starting with slide-
$('[id^=slide-]').on('click', function(e){
// some code.
window.location.href = $(this).data('webpage');
}
1) you are comparing $a.id, that is string, to object $('#slide-1285');.
2) To simplify:
$(document).ready(function(){
$('.a').click(function(e){
e.preventDefault();
window.location = $(this).attr('href');
});
});
<a href='http://google.com' class='a'>Google!</a><br/>
<a href='http://stackoverflow.com' class='a'>SO!</a><br/>
jQuery objects have no id property. You need to do attr('id'), or just get the id property of the plain DOM object. Additionally, jQuery objects are never going to equal each other. Third, you want to check if the clicked element has a certain ID, which can be done using .is().
In sum, you could do one of these:
Comparing strings:
$('#slidernavigation > a').on('click', function(e){
if(this.id == '#slide-1285'){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Using .is():
$('#slidernavigation > a').on('click', function(e){
if($(this).is('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Or, just let the browser do its thing. Give your <a>s href attributes, and they'll function as links, even without JS.
instead of writing $.id
you should write
$a.attr('id')
and this should be checked like this :-
if( $a.attr('id') == slide-1285)
not the way you are doing :)
Try
var pages = [{"slide-1285" : "http://webpage1"}
, {"slide-1286" : "http://webpage2"}
, {"slide-1287" : "http://webpage3"}
, {"slide-1288" : "http://webpage4"}
];
$('#slidernavigation > a').on('click', function(e) {
e.preventDefault();
var nav = e.target.id;
$.grep(pages, function(page) {
if (nav in page) {
window.location.href = page[nav];
}
})
});
jsfiddle http://jsfiddle.net/guest271314/2nf97dfr/
<div id="a">
dhjdfd
</div>
$('#a').on('click',function(e){
var clickedElement= e.srcElement;
if($(clickedElement).attr("id") == "abc"){
//do something
}
});
just use e.srcElement to get the element reference and then get its id.. and btw u can use switch case rather than multiple if else statements ..
working fiddle link

get clicked link-button ID where all buttons already bind to one function

the app receive a n html dive and create a page and append it to the app
I bind all link-buttons in set of pages to one function
which will do different tasks depends on the id of the page
now I have a problem when a page has more than one link-button
I need the ID of the clicked button
Html:
<a id="x">x </a>
<a id="y">y </a>
Js:
var btns = [];
$('#page-' + newpages[j].pageID + ' a').each(function () {
btns.push({
id: this.id,
value: this.value,
name: this.name
});
});
for (i in btns) {
$('#' + btns[i].id).bind('click', function () {
test(btns[i].id)
});
// bin all buttons in current page to test()
}
};
};
function test(x) {
var page = $('.ui-page-active').attr('id');
/////////
//here I'm trying to ge the ID of clicked button of that page (each ID means something)
var pos = '';
$('#' + page + ' a').click(function () {
//Get the id of this clicked item
var BID = $(this).attr("id");
alert(BID);
send(BID);
});
Why don't you just bind to the click event on each button independently? If you switch by ID anyway why go through a generic function, any shared functionality can be abstracted into a function and utilized by each click handler so you loose nothing.

form action url change depending on #tag

Is it possible to change a forms action Url with jQuery/js depending on a browser #tag?
The tabs are working correctly I just need the action to change as well.
Here is the tab js I am currently using, I am also using the jQuery Address Plugin also:
var QTABS = {
init: function () {
// attached onload and change event to address plugin
$.address.init(function(event) {
// first load, set panel
QTABS.setPanel(event);
}).change(function(event) {
// if the url changes, set panel
QTABS.setPanel(event);
});
},
// the core function to display correct panel
setPanel: function (event) {
// grab the hash tag from address plugin event
var hashtag = event.pathNames[0];
// get the correct tab item, if no hashtag, get the first tab item
var tab = (hashtag) ? $('.tabs li a[href=#' + hashtag + ']') : $('.tabs li:first a');
// reset everything to default
$('.tabs li').removeClass('activeTab');
$('.tab_container .tab_content').hide();
// if hashtag is found
if (hashtag) {
// set current tab item active and display correct panel
tab.parent().addClass('activeTab');
$('.tab_container .tab_content:eq(' + (tab.parent().index()) + ')').show();
} else {
// set the first tab item and first panel
$('.tabs li:first').addClass('activeTab');
$('.tab_container .tab_content:first').show();
}
if ($('.tabs').length)
{
// change the page title to current selected tab
document.title = tab.attr('title');
}
}
}
// Execute this script!
QTABS.init();
This is what i ahve used successfully
$("#myDelete").click(function(){
$('#myForm').attr("action", "accounttrandelete.php");
$("#myForm").submit();
return false;
});
$("#myEdit").click(function(){
$('#myForm').attr("action", "accounttranedit.php");
$("#myForm").submit();
return false;
});
$("#myRec").click(function(){
$('#myForm').attr("action", "accounttranrec.php");
$("#myForm").submit();
return false;
});
$("#myUnRec").click(function(){
$('#myForm').attr("action", "accounttranunrec.php");
$("#myForm").submit();
return false;
});
Because I don't know where the form is and how you want to access it. If you want change the action url to do this:
$("form").attr("action", "Put your new Url here");
UPDATE:
$("#tag")..attr("action", "Put your new Url here");
If you want to use standard Javascript you can change as follow:
document.forms[0].action = "Put your new Url here";
Note: you can replace forms[0] by the name of your form.
UPDATE:
If you have a form with an id then its similar to above method call:
document.getElementById("tag").action = "Put your new Url here";

Categories

Resources