I added tabs to a section of my page I am working on (stridertechnologies.com/stoutwebsite/products.php)using the steps found at this website: http://code-tricks.com/create-a-simple-html5-tabs-using-jquery/
I want to link to the different tabs from the home page, but I am not sure how to do that outside of anchor names with html and that doesn't work with this, and there aren't any instructions on how to do it on the site.
It seems like there should be something really simple I can add to my javascript to detect which link they clicked on and make it the active tab.
javascript:
;(function($){
$.fn.html5jTabs = function(options){
return this.each(function(index, value){
var obj = $(this),
objFirst = obj.eq(index),
objNotFirst = obj.not(objFirst);
$("#" + objNotFirst.attr("data-toggle")).hide();
$(this).eq(index).addClass("active");
obj.click(function(evt){
toggler = "#" + obj.attr("data-toggle");
togglerRest = $(toggler).parent().find("div");
togglerRest.hide().removeClass("active");
$(toggler).show().addClass("active");
//toggle Active Class on tab buttons
$(this).parent("div").find("a").removeClass("active");
$(this).addClass("active");
return false; //Stop event Bubbling and PreventDefault
});
});
};
}(jQuery));
This answer is from a duplicated question here: https://stackoverflow.com/a/20811416/3123649.
You could pass the tab div id in the url from the link and use that to select.
Home page links from index.html:
tile
metal
Add this javascript to the tab page
<script type="text/javascript">
// To get parameter from url
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$.extend($.expr[':'], {
attrNameStart: function (el, i, props) {
var hasAttribute = false;
$.each(el.attributes, function (i, attr) {
if (attr.name.indexOf(props[3]) !== -1) {
hasAttribute = true;
return false;
}
});
return hasAttribute;
}
});
// deselect tabs and select the tab by id
function focusTab(id) {
$("#tile").hide().removeClass("active");
$("#metal").hide().removeClass("active");
$("#shingle").hide().removeClass("active");
$("#flat").hide().removeClass("active");
$("#custom").hide().removeClass("active");
var toggle = $(id).parent().find("div");
toggle.hide().removeClass("active");
$('a:attrNameStart(data-toggle)').removeClass("active");
var id1 = getParameterByName("tabId");
var toggler = $('*[data-toggle=' + id1 + ']');
$(toggler).addClass("active");
$(id).show().addClass("active");
}
$(function() {
$(".tabs a").html5jTabs();
// Get the tab id from the url
var tabId = "#" + getParameterByName("tabId");
// Focus the tab
focusTab(tabId);
});
</script>
EDIT: Replace the original focusTab function with the edit. Also add the extend function attrNameStart. This should deselect the default active tab.
EDIT2: focusTab had a bug, it should work now
** I looked at your site and my solutions seems to be working for you. One thing I noticed. You initialize the html5jTabs() twice.
Remove the first call at the top
<script type="text/javascript">
$(function() {
$(".tabs a").html5jTabs();
});
</script>
How about something like this? Basically we are taking the value of data-toggle in our buttons, and passing it into the selector for each tab content
JS
$('a[data-toggle]').on('click', function () {
var dataToggle = $(this).data('toggle');
$('.tabContent > div').removeClass('active');
$('.tabContent > div#'+dataToggle+'').addClass('active');
});
working example:
http://jsfiddle.net/whiteb0x/VdeqY/
Related
I'm trying to modify a URL based on the user either (or both) clicking one of 3 text links and/or entering a keyword into a text input. Currently, I have it working, but doing both overwrites the other. For example, if I click on "Scholarships," it looks good. If I enter a word into the text input, it works but overwrites my previous selection. Please be kind, as I'm new to JS.
A CodePen:
https://codepen.io/admrbsn/pen/QOQmMN
My JS:
$(document).ready(function () {
var select = $('.custom-option');
var input = document.querySelector("#search-input");
select.click(function(e) {
var type = e.target.getAttribute('data-value');
var link = "/search/" + type + "/?searchterm=";
document.querySelector('#searchLink').href = link;
});
input.addEventListener("change", function() {
var keyword = this.value;
var link = "/search/?searchterm=" + keyword;
document.querySelector('#searchLink').href = link;
});
});
Try to reuse code, for example create a function that updates the link from both actions.
example:
function updateLink() {
var href = '';
if (link)
href = "/search/" + link + "/?searchterm=" + text;
else
href = "/search/?searchterm=" + text;
document.querySelector('#searchLink').href = href;
}
complete example:
https://codepen.io/anon/pen/ooEywW
Well yes, the change event is firing and is running the second block of code (input.addEventListener("change", function() {) that sets it without the type. I'd recommend setting variables outside of those events, and then changing the HREF with a separate code block:
$(document).ready(function () {
var select = $('.custom-option');
var input = document.querySelector("#search-input");
var type = '';
var searchterm = '';
var updateLink = function () {
var link = "/search/" + type + "?searchterm=" + searchterm;
document.querySelector('#searchLink').href = link;
}
select.click(function(e) {
type = e.target.getAttribute('data-value');
updateLink();
});
input.addEventListener("change", function() {
searchterm = this.value;
updateLink();
});
});
Also I'm not sure why you're using document.querySelector when you're already using jQuery. Why not just do $("#search-input")?
I have a server that dynamically(asp.net ) generate webpages that I can't alter.
On all pages I would like to capture all buttons clicked.
In JSFiddle https://jsfiddle.net/forssux/aub2t6gn/2/ is an example..
$(".checkout-basket").click (function ()
The first alert shows the 3 possible values,
but not the chosen item..
$(".button.button-dl").click(function ()
In jsfiddle this part doesn't get executed
Strangely on my real webpage I get the button clicked...but when I put it in the If then construction it fails to console.log the chosen item..
I hope somebody can explain me how to get these..
Kind Regards
Guy Forssman
//$("div.detail-info,table.checkout-basket").click(function () {
// var knopje = $(this).attr("class")//.split(" ");
// console.log(knopje + " knopje was clicked");
// if(knopje.indexOf("detail-info") > -1) {
// console.log("div class detail-info is clicked");
// }
// else if (knopje.indexOf("checkout-basket") > -1) {
// console.log("table class checkout-basket is clicked");
// }
// else {
// alert ("er is op iets anderes gedrukt");
// }
// capture click on download button in checkout-basket page
$(".checkout-basket").click (function () {
basket =[];
item="";
str = $(this).text();
str = str.replace(/\s\s+/g, ' ');
var str = str.match(/("[^"]+"|[^"\s]+)/g);
console.log("Array ",str);
for(var i=0;i<str.length;i++){
if(str[i] === "verwijder"){
console.log("Item= ",str[i+1]);
item = str[i+1];
basket.push(item);}
}
console.log("Basket contains ",basket);
//console.log("idValBasket ",idVal);
var test = idVal.replace(/\$/gi, "_").slice(0,-6);
console.log("test ",test);
var element = test.substr(test.length - 2)-1;
console.log("element ",element);
element=element-1;
item = basket[element];
console.log("Item finaal is ",item);
});
$(".button.button-dl").click(function () {
var addressValue = $(this).attr('href');
console.log("addresValue Basket",addressValue );
var re = /'(.*?)'/;
var m = addressValue.match(re);
console.log (" m basket is ",m);
if (m != null)
idVal = (m[0].replace(re, '$1'));
console.log("idVal Basket",idVal);
});
//This section captures the download in the detail page
$(".button").click(function () {
var downloadItem = document.getElementsByTagName("h1")[0].innerHTML
console.log("addresValue detail",downloadItem );
});
I never use click function, use on(*event*,...) instead:
$(".checkout-basket").on("click", function (){ /* CODE */ });
Check if visually there are a layout over the a layuot (a div, span, etc.)
Maybe a strange question and maybe i got it wrong, but why do you use push ?? if you want to delete an item ? btw also the example isn't working so maybe that is your problem
I'm sending a specific value through url and after that my page get refreshes.
The URL value is dynamic.Whenever URL sets I want to show div which is already hidden.
<button id="show_id" onclick="location.href='opdcasepaperreport.php?patient_nm='+document.getElementById('patient_id').value;" > View Report </button>
When user clicks on View Report , report div will be displayed.
I tried following 2 coding methods:
$( document ).ready(function()
{
$("#show_id").click(function()
{
$('#main').toggle();
});
});
and
$(document).ready(function ()
{
if(window.location.href.indexOf("?patient_nm"))
{
//alert("your url contains ");
//show code;
}
});
in 1st case because of page refresh div get visible and un visible again.
Is there any solution for this like in php if(isset(---)){//do this;}
Changing location.href value will refresh the page anyway.
In order to hide/show div depending on url value you need to:
get the value by searching in url params.
show / hide div.
Get URL params.
You can use this script in order to get url params:
var getQuery = function () {
var url_params = {};
var query = window.location.search.substring(1);
if (query.length === 0) return false;
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof url_params[pair[0]] === "undefined") {
url_params[pair[0]] = pair[1];
} else if (typeof url_params[pair[0]] === "string") {
var arr = [ url_params[pair[0]], pair[1] ];
url_params[pair[0]] = arr;
} else {
url_params[pair[0]].push(pair[1]);
}
}
return url_params;
};
It will return an object (key, value).
Show / Hide div
If you using jQuery, you can simply is .toggle()
$("#your_div_name").toggle();
Or by using .show() / .hide()
So:
var query = getQuery();
if (query && query.some_param !== undefined) {
$("#your_div_name").show()
} else {
$("#your_div_name").hide()
}
But it's better not to use url params in order to change view.
Have fun.
How about this:
$("#show_id").click(function(e)
{
e.preventDefault();//this will prevent page refresh
$('#main').toggle();
});
Try following code:
$( document ).ready(function()
{
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var hasParam = getParameterByName('patient_nm');
if(hasParam !== 'undefined') {
$('#main').toggle();
}
});
As per your code, on button click the element will get toggled but after that the page gets refreshed immediately. On page refresh the element will be hidden again, so you are not able to view the effect.
As per my code above, when the page refreshes/loads, it will search for the parameter "patient_nm" that you are adding in the URL. If this parameter is not empty it will toggle the element. Since this process happens after page load, you will be able to see the results.
Hope this helps.
I'm using jquery UI to create tabs. Requirement is when i select tab2 or any other tab and reload/refresh the page, focus should be on the selected tab. Please find the fiddle http://jsfiddle.net/CnEUh/500/
I have gone through many online forums but could not get the expected result.
I followed the link Set Jquery ui active tab on page load/reload , but didn't got the result.
Tried the below code :
$(document).ready(function() {
$("#tabs").tabs({active: tabs-2});
// Set active tab on page load
var SelectedTab = tabs-2;
if(tabSelectedId!=""){
$("#tabs").tabs({selected: tabSelectedId});
}
});
Please suggest how can i keep the focus on the selected tab on page reload. My fiddle http://jsfiddle.net/CnEUh/500/
You can accomplish it by using location.href
On click, just add #tab=2 and then on page load, here you can retrieve location.href and choose which tav is selected.
Add jquery.cookie.js library and the following code
$(document).ready(function() {
var $tabs = $( "#tabs" ).tabs({
activate: function(event ,ui){
$.cookie('active_tab', ui.newTab.index(), { path: '/' });
}
});
var selectedIndex=parseInt($.cookie('active_tab'));
if(selectedIndex) {
$tabs.tabs({ active: selectedIndex });
$('#tabs').find("ul:first li:nth-child(" + (selectedIndex + 1) + ")").find('a').trigger('click');
}
// set cookie on tab select
});
Or without jquery.cookie.js, pass the active tab index as a parameter
var activeTab;
var $tabs = $("#tabs").tabs({
activate: function (event, ui) {
activeTab = ui.newTab.index();
}
});
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
// Now you can get the parameters you want like so:
var selectedIndex = parseInt(params.selectedIndex);
if (selectedIndex) {
$tabs.tabs({
active: selectedIndex
});
$('#tabs').find("ul:first li:nth-child(" + (selectedIndex + 1) + ")").find('a').trigger('click');
}
$('#tabs').click(function() {
window.location.href = window.location.href.replace( /[\?#].*|$/, "?selectedIndex="+activeTab );
});
Hopefully it works.
Thanks
So far I have done
jQuery:
function addURL(element)
{
var baseZipCode = 48180;
$(element).attr('href', function() {
return this.href + baseZipCode;
});
}
html:
<a onclick="addURL(this)" href="http://www.weather.com/weather/today/" target="_blank">Click this</a>
My problem is when user clicks on link and the new window open everything is ok, but when the user clicks on the link again without a refresh, the variable is added twice to the link.
For example:
First time:
http://www.weather.com/weather/today/48180
Second time:
http://www.weather.com/weather/today/4818048180
It doesn't act right until you do a page refresh, any help would be appreciated. Thanks in advance
Replace your addURL function with
function addURL(element)
{
var baseZipCode = '48180';
if (element.href.slice(-baseZipCode.length) !== baseZipCode){
element.href += baseZipCode;
}
}
there is no jQuery involved..
You can try it with jQuery.fn.one
Javascript:
jQuery("a").one("click", function(){ // Set a handler that execute once
var baseZipCode = 48180;
this.href += baseZipCode; //same as "this.href = this.href + baseZipCode"
});
HTML:
Click this
Maybe you will need to add some class to <a> tags to differ it from another ones
This should be:
function addURL(element)
{
var baseZipCode = 48180;
element.href = (element.href + baseZipCode)
.replace(baseZipCode + baseZipCode, baseZipCode);
}
return this.href.indexOf(baseZipCode) != -1 ? this.href : this.href + baseZipCode;