I am new to JQuery and web development in general and hence facing a troubling issue during development. My website interface looks like below:
When a user clicks on any checkbox (for referral purposes, I have selected the box above 'chk2') and then clicks on the 'Show Evidence' button (box 2 in the image), I want the user to be able to highlight portions of the article displayed in the adjacent iframe. I am using a text highlighter Jquery plugin I found on the web. The code for the click event of the 'Show Evidence' button looks like:
$('.show_evidence').click(function(event){
var iframe = document.getElementById('myiFrame');
var hltr = new TextHighlighter(iframe.contentDocument.body);
hltr.setColor("yellow");
});
The above code works fine.
Now, I want to set the highlight color (i.e. hltr.setColor("blue")) to blue when the user clicks on the checkbox 'Unselect' (box 3 in the image). For that I need to be able to access the 'hltr' object I have defined above (i.e. inside the 'click' event handler for '.show_evidence'). Also I want to set the highlight color back to 'yellow' when the user unchecks the 'Unselect' checkbox.
$(".unselect").change(function() {
if(this.checked) {
//Something like - hltr.setColor("blue");
}
else {
// Something like - hltr.setColor("yellow");
}
});
Finally, I also want to unset or undefine the object 'hltr' when the user clicks on the link 'Hide Datums' (box 1 in the image).
So my question is how do I access the hltr object inside the event handlers for .Unselect and the 'Hide Datums' link.
After a lot of stackoverflow surfing, I found that I could use external variables but I am not sure whether that will work for objects. Also, is there a universally recommended design that I should use or follow? What is the best way to achieve what I want?
Looking forward to your suggestions. Please help!
Regards,
Saswati
One way you can go about is extract the lines of code which does the element selection to a separate method.
var hltr;
function getBodyElementOfIframe() {
var iframe = document.getElementById('myiFrame');
if(!hltr) {
hltr = new TextHighlighter(iframe.contentDocument.body);
}
return hltr;
}
Call that method where you want to access the element and then set the color.
$(".unselect").change(function() {
var hltr = getBodyElementOfIframe();
if(this.checked) {
hltr.setColor("blue");
}
else {
hltr.setColor("yellow");
}
});
There are a number of ways to solve it, but one simple way to do it would be to move the variable outside the scope of the method so that it is accessible through out.
I would put it inside on ready.
$(document).ready(function () {
var hltr = {};
$('.show_evidence').click(function(event){
var iframe = document.getElementById('myiFrame');
hltr = new TextHighlighter(iframe.contentDocument.body);
hltr.setColor("yellow");
});
$(".unselect").change(function() {
if(this.checked) {
//Something like - hltr.setColor("blue");
}
else {
// Something like - hltr.setColor("yellow");
}
});
})();
If you need the variable inside several functions, declare it outside of all of them.
$(function(){
var iframe = document.getElementById('myiFrame');
var hltr = new TextHighlighter(iframe.contentDocument.body);
$('.show_evidence').click(function(event){
hltr.setColor("yellow");
});
});
When your event handlers fire, they'll be updating this var and it will be accessible to the next handler called.
I have a webpage with images.
A user can click on images to show() or hyde() these images.
Sometimes, the user opens a popup to watch a video.
Then the code hide() all elements previously opened.
When the user closes the video, i need to know which elements was previously opened in order to show only them.
What is the best way to do that ?
What i've done :
I've created an array and i push images names into it.
var arr_popup_open = [];
Then, this function is called when user open a popup and hide all elements :
function toggleAllPopup() {
if( $('#popup_micro_1').is(":visible"))
{
$('#popup_micro_1').hide();
arr_popup_open.push('#popup_micro_1');
}
if( $('#popup_micro_2').is(":visible"))
{
$('#popup_micro_2').hide();
arr_popup_open.push('#popup_micro_2');
}
if( $('#popup_micro_3').is(":visible"))
{
$('#popup_micro_3').hide();
arr_popup_open.push('#popup_micro_3');
}
}
// and so on ... I have 7 images so it seems it's not very well optimized
When i need to show only images previously opened, i execute this code, a loop to show() elements in array.
$('#close_pop_up').click(function() {
for(var i= 0; i < arr_popup_open.length; i++)
{
$(arr_popup_open[i]).show();
}
});
What do you think about that ? Is there a better way to to do it ?
There are a few ways you could go about this with jQuery. Your way should work, but if you want to reduce the amount of code you could do something like:
var visibleDivs = $('div:visible', '#ContainerDiv');
Alternatively you could add a specific class to all visible elements when you show them and use:
var visibleDivs = $('.someClassName');
When hiding them due to your popup, you can store the list in the data of any element. In this case, putting it on #close_pop_up might make sense:
visibleDivs.hide();
$('#close_pop_up').data('myDivs', visibleDivs);
When you want to show them again in your click function:
$('#close_pop_up').click(function() {
$(this).data('myDivs').show();
});
Looks fine to me. Just remember to clear arr_popup_open in the start of the toggleopen function.
The alternative you could do if you really wanted is to keep the information of what is open or closed in Javascript variables that get updated when you open and close things. This way you don't need to depend on complex things such as is(:visible)
I want to add a toolbar button before the firefox search container in my addon. But it is completely clearing my navigation bar.
I suspect the offending code is due to an empty array or something but i cant be certain.
//insert before search container
if(navBar && navBar.currentSet.indexOf("mybutton-id")== -1 )//navBar exist and our button doesnt
{
var arrayCurrentSet= navBar.currentSet.split(',');
var arrayFinalSet= [];//empty at first
if(arrayCurrentSet.indexOf("search-container") != -1)//if search-container exists in current set
{
// check item by item in current set
var i= null;
while(i=arrayCurrentSet.shift() != undefined)
{
if(i == "search-container")//"search-container" found !!
{
/*insert our button after it but only if our button does not already exist*/
if(arrayFinalSet.indexOf("mybutton-id") == -1) arrayFinalSet.push("mybutton-id");
}
arrayFinalSet.push(i);
dump("arrayFinalSet "+ i);
}
}
else //damn search-container doesnt exist
{
arrayFinalSet= arrayCurrentSet;
arrayFinalSet.push("mybutton-id");//add our button to the end of whatever is available in nav bar
}
//set new navBar
navBar.currentSet= arrayFinalSet.join(',');
}
The full code is available
https://builder.addons.mozilla.org/addon/1052494/latest/
http://jsfiddle.net/CQ4wA/
I'm not too sure why the navigation bar has been removed, but I think it would be better to approach this from a different angle. Rather than messing around with an array of strings, try using DOM methods instead.
e.g.
var sC=navBar.querySelector("#search-container");
navBar.insertBefore(btn, sC);
The code you have here seems to work - but the toolbar needs to find your button somehow. Your current code doesn't even insert the button into the document, meaning that the toolbar has no chance to find it by its ID. It should be in the toolbar palette palette however, the palette also determines which buttons the user can choose from when customizing the toolbar. So you probably want to do something like this first:
var toolbox = navBar.toolbox;
toolbox.palette.appendChild(btn);
You might also want to simplify your code:
var arrayCurrentSet = navBar.currentSet.split(',');
var insertionPoint = arrayCurrentSet.indexOf("search-container");
if (insertionPoint >= 0)
arrayCurrentSet.splice(insertionPoint, 0, "mybutton-id");
else
arrayCurrentSet.push("mybutton-id");
navBar.currentSet = arrayCurrentSet.join(',');
And finally, you probably want to make the browser remember the current button set, it doesn't happen automatically:
document.persist(navBar.id, "currentset");
Note that the button that will be inserted into the toolbar is not the same as the button you added to the palette - the toolbar code clones the button, with one copy being left in the palette. So event listeners added via addEventListener will sadly be lost. It is better to use a command attribute and insert a <command> element into the document that you will attach your listener to.
Note: in XUL you usually want the command and not the click event - unless you are really interested in mouse clicks only and want to ignore the button being triggered by keyboard or other means.
Is there any way to increase the time a drop-down menu created stays on screen? The drop down menu just appears and disappears as I touch the cursor. The drop-down was created using Prototype.
Use a different drop down menu:
Here's over 25 that might better suit your needs:
http://www.noupe.com/css/multilevel-drop-down-navigation-menus-examples-and-tutorials.html
Or mention what drop down menu you are using so we can at least discover the option for you!
Whatever function you have attached to the rolloff of the menu to make it disappear, add that code to another function and use a setTimeout() call to pause for a time before removing the menu.
Example:
Old Code
var closeMenu = function() {
$('menu').hide();
};
New Code
var hideMenu = function() {
$('menu').hide();
};
var closeMenu = function() {
setTimeout(hideMenu, 5000);
};
With that change, you've now delayed the menu's disappearing act for 5 seconds. Probably don't want to take that long but you get the idea.
I know this specific question has been asked before, but I am not getting any results using the bind() event on the jQuery UI Tabs plugin.
I just need the index of the newly selected tab to perform an action when the tab is clicked. bind() allows me to hook into the select event, but my usual method of getting the currently selected tab does not work. It returns the previously selected tab index, not the new one:
var selectedTab = $("#TabList").tabs().data("selected.tabs");
Here is the code I am attempting to use to get the currently selected tab:
$("#TabList").bind("tabsselect", function(event, ui) {
});
When I use this code, the ui object comes back undefined. From the documentation, this should be the object I'm using to hook into the newly selected index using ui.tab. I have tried this on the initial tabs() call and also on its own. Am I doing something wrong here?
If you need to get the tab index from outside the context of a tabs event, use this:
function getSelectedTabIndex() {
return $("#TabList").tabs('option', 'selected');
}
Update:
From version 1.9 'selected' is changed to 'active'
$("#TabList").tabs('option', 'active')
For JQuery UI versions before 1.9: ui.index from the event is what you want.
For JQuery UI 1.9 or later: see the answer by Giorgio Luparia, below.
If you're using JQuery UI version 1.9.0 or above, you can access ui.newTab.index() inside your function and get what you need.
For earlier versions use ui.index.
UPDATE [Sun 08/26/2012] This answer has become so popular that I decided to make it into a full-fledged blog/tutorial
Please visit My Blog Here to see the latest in easy access information to working with tabs in jQueryUI
Also included (in the blog too) is a jsFiddle
¡¡¡ Update! Please note: In newer versions of jQueryUI (1.9+), ui-tabs-selected has been replaced with ui-tabs-active. !!!
I know this thread is old, but something I didn't see mentioned was how to get the "selected tab" (Currently dropped down panel) from somewhere other than the "tab events".
I do have a simply way ...
var curTab = $('.ui-tabs-panel:not(.ui-tabs-hide)');
And to easily get the index, of course there is the way listed on the site ...
var $tabs = $('#example').tabs();
var selected = $tabs.tabs('option', 'selected'); // => 0
However, you could use my first method to get the index and anything you want about that panel pretty easy ...
var curTab = $('.ui-tabs-panel:not(.ui-tabs-hide)'),
curTabIndex = curTab.index(),
curTabID = curTab.prop("id"),
curTabCls = curTab.attr("class");
// etc ....
PS. If you use an iframe variable then .find('.ui-tabs-panel:not(.ui-tabs-hide)'), you will find it easy to do this for selected tabs in frames as well.
Remember, jQuery already did all the hard work, no need to reinvent the wheel!
Just to expand (updated)
Question was brought up to me, "What if there are more than one tabs areas on the view?"
Again, just think simple, use my same setup but use an ID to identify which tabs you want to get hold of.
For example, if you have:
$('#example-1').tabs();
$('#example-2').tabs();
And you want the current panel of the second tab set:
var curTabPanel = $('#example-2 .ui-tabs-panel:not(.ui-tabs-hide)');
And if you want the ACTUAL tab and not the panel (really easy, which is why I ddn't mention it before but I suppose I will now, just to be thorough)
// for page with only one set of tabs
var curTab = $('.ui-tabs-selected'); // '.ui-tabs-active' in jQuery 1.9+
// for page with multiple sets of tabs
var curTab2 = $('#example-2 .ui-tabs-selected'); // '.ui-tabs-active' in jQuery 1.9+
Again, remember, jQuery did all the hard work, don't think so hard.
var $tabs = $('#tabs-menu').tabs();
// jquery ui 1.8
var selected = $tabs.tabs('option', 'selected');
// jquery ui 1.9+
var active = $tabs.tabs('option', 'active');
When are you trying to access the ui object? ui will be undefined if you try to access it outside of the bind event.
Also, if this line
var selectedTab = $("#TabList").tabs().data("selected.tabs");
is ran in the event like this:
$("#TabList").bind("tabsselect", function(event, ui) {
var selectedTab = $("#TabList").tabs().data("selected.tabs");
});
selectedTab will equal the current tab at that point in time (the "previous" one.) This is because the "tabsselect" event is called before the clicked tab becomes the current tab. If you still want to do it this way, using "tabsshow" instead will result in selectedTab equaling the clicked tab.
However, that seems over-complex if all you want is the index. ui.index from within the event or $("#TabList").tabs().data("selected.tabs") outside of the event should be all that you need.
this changed with version 1.9
something like
$(document).ready(function () {
$('#tabs').tabs({
activate: function (event, ui) {
var act = $("#tabs").tabs("option", "active");
$("#<%= hidLastTab.ClientID %>").val(act);
//console.log($(ui.newTab));
//console.log($(ui.oldTab));
}
});
if ($("#<%= hidLastTab.ClientID %>").val() != "")
{
$("#tabs").tabs("option", "active", $("#<%= hidLastTab.ClientID %>").val());
}
});
should be used. This is working fine for me ;-)
In case anybody has tried to access tabs from within an iframe, you may notice it's not possible. The div of the tab never gets marked as selected, just as hidden or not hidden. The link itself is the only piece marked as selected.
<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-focus">Tab 5</li>
The following will get you the href value of the link which should be the same as the id for your tab container:
jQuery('.ui-tabs-selected a',window.parent.document).attr('href')
This should also work in place of: $tabs.tabs('option', 'selected');
It's better in the sense that instead of just getting the index of the tab, it gives you the actual id of the tab.
the easiest way of doing this is
$("#tabs div[aria-hidden='false']");
and for index
$("#tabs div[aria-hidden='false']").index();
In case if you find Active tab Index and then point to Active Tab
First get the Active index
var activeIndex = $("#panel").tabs('option', 'active');
Then using the css class get the tab content panel
// this will return the html element
var element= $("#panel").find( ".ui-tabs-panel" )[activeIndex];
now wrapped it in jQuery object to further use it
var tabContent$ = $(element);
here i want to add two info the class .ui-tabs-nav is for Navigation associated with and .ui-tabs-panel is associated with tab content panel. in this link demo in jquery ui website you will see this class is used - http://jqueryui.com/tabs/#manipulation
I found the code below does the trick. Sets a variable of the newly selected tab index
$("#tabs").tabs({
activate: function (e, ui) {
currentTabIndex =ui.newTab.index().toString();
}
});
$( "#tabs" ).tabs( "option", "active" )
then you will have the index of tab from 0
simple
You can post below answer in your next post
var selectedTabIndex= $("#tabs").tabs('option', 'active');
Try the following:
var $tabs = $('#tabs-menu').tabs();
var selected = $tabs.tabs('option', 'selected');
var divAssocAtual = $('#tabs-menu ul li').tabs()[selected].hash;
You can find it via:
$(yourEl).tabs({
activate: function(event, ui) {
console.log(ui.newPanel.index());
}
});
Another way to get the selected tab index is:
var index = jQuery('#tabs').data('tabs').options.selected;
$("#tabs").tabs({
load: function(event, ui){
var anchor = ui.tab.find(".ui-tabs-anchor");
var url = anchor.attr('href');
}
});
In the url variable you will get the current tab's HREF / URL
take a hidden variable like '<input type="hidden" id="sel_tab" name="sel_tab" value="" />' and on each tab's onclick event write code like ...
<li><a href="#tabs-0" onclick="document.getElementById('sel_tab').value=0;" >TAB -1</a></li>
<li><a href="#tabs-1" onclick="document.getElementById('sel_tab').value=1;" >TAB -2</a></li>
you can get the value of 'sel_tab' on posted page. :) , simple !!!
If you want to ensure ui.newTab.index() is available in all situations (local and remote tabs), then call it in the activate function as the documentation says:
$("#tabs").tabs({
activate: function(event, ui){
alert(ui.newTab.index());
// You can also use this to set another tab, see fiddle...
// $("#other-tabs").tabs("option", "active", ui.newTab.index());
},
});
http://jsfiddle.net/7v7n0v3j/
$("#tabs").tabs({
activate: function(event, ui) {
new_index = ui.newTab.index()+1;
//do anything
}
});