I'm new to working with JS/jQuery, I've been currently trying to figure out how to make this work, by trying many different ways that I've found here and on different sites, and am unable to get this working.
I have a website that has tabs, that changes a div's content when the click on the buttons in the menu. This all works fine, but I want to be able to link to each separate "page" using hash tags example.com/#tab-1
HTML:
<div class="tabWrapper">
<div class="tabContent">
<div class="label">TAB 1</div>
<?php include 'tab1.php'; ?>
</div>
<div class="tabContent">
<div class="label">TAB 2</div>
<?php include 'tab2.php'; ?>
</div>
tabWrapper looks like this after being generated
<div class="tabWrapper">
<ul class="tabs">
<li class="tab-1">TAB 1</li>
<li class="tab-2">TAB 2</li>
</ul>
JS :
// Generate tab navigation
if ($('div.tabWrapper').length != 0)
{
$('div.tabWrapper').each(function()
{
// Prepare tab output
var printTabs = '<ul class="tabs">';
var tabContent = $(this).find('.tabContent');
var tabCount = tabContent.length;
$(tabContent).each(function(key)
{
// Hide tab if it is not the first
if (key != 0)
{
$(this).hide();
}
// Get label for tab
var label = $(this).find('.label').text();
// Use a number if no label was given
if (!label)
{
label = 'Tab ' + (key + 1);
}
// Add id to tab content
$(this).addClass('tab-' + key);
printTabs+= '<li class="tab-' + key + '">' + label + '</li>';
});
// Add tabs
$(this).prepend(printTabs + '</ul>');
$(this).find('li:first').addClass('active');
});
}
// Handle click on tabs
$('.tabWrapper').delegate('ul.tabs li', 'click', function()
{
// Deny click on active element
if ($(this).is('.active'))
{
return false;
}
// Get tab id
var id = $(this).attr('class').split('-');
id = id[1];
// Display and animate new tab content
var parent = $(this).parent().parent();
parent.find('ul.tabs li').removeClass('active');
$(this).addClass('active');
parent.find('.tabContent').hide()
parent.find('.tab-' + id).animate({ opacity: 'show' }, animationSpeed);
});
Here is what I was trying to add, which I don't think is correct
function hash() {
if(window.location.hash){
var hash = window.location.hash.substring(1);
$("." + hash).click();
}
}
which I added in the js file just above
$('.tabWrapper').delegate('ul.tabs li', 'click', function()
I'm not sure how far I'm off with that code, as it doesn't seem to work at all. I just want it to see if there is a hash tag in the url, and if there is then run the click function to change the content.
I hope I explained what I was looking for clear enough. I'd very much appreciate any help with this.
Thank you.
UPDATE:
I updated the code with setInterval as per chiliNUT's suggestion, however it still doesn't appear to be working.
setInterval(hash,1000);
function hash() {
if(window.location.hash){
var hash = window.location.hash.substring(1);
$("." + hash).click();
}
}
UPDATE 2:
Still unable to get this working, anyone able to help?
Thanks.
My tip is using anchor tags as well.
Link
That will open example.com#tab1
The control on page load:
$( document ).ready(function() {
if(window.location.hash == "#tab1"){
$("#someId").click();
}
});
Why not just use anchor tags?
Button to open tab 1
Related
I have a variable called links that stores any URLs that have been visited previously.
I need to match the URLs on the page with the results from the variable. If they match assign the class "visited" to just those links.
So for example if my page has:
<a href="link1.html">
<a href="link2.html">
<a href="link3.html">
<a href="link4.html">
<a href="link5.html">
and the links variable has:
link1.html
link3.html
link4.html
In this case like to add the class "visited" to the links that are stored in the variable link1.html, link3.html and link4.html in this case. There are loads of links with all sorts of text. These ones are just for a simple example.
This is what I have so far:
$(document).ready(function() {
$('#rightbox li a').each(
function(intIndex){
var links = $(this).attr('href');
console.log(links);
$.ajax({
url: links,
type:'HEAD',
error: function() { },
success: function() {
var visited = (links)
$("#visitedLinkContainer").append(visited);
$(this).attr('href').addClass("visited");`
// I tried this but it adds visited to everylink which I knew would, but I don't know what to put here`
}
});
});
});
This is for a personal project at home. I'm using local storage at the moment, but I'd prefer to do it this way if possible.
Thank you for any help received
Use the following code:
links.forEach(function(link) {
$('#rightbox li a[href="' + link + '"]').addClass('visited');
});
The jQuery selector [<attribute>="<value>"] selects elements that their <attribute> equals to <value>.
I've created an example: https://codepen.io/anon/pen/OwMbgp
html
Link1
Link2
Link3
Link4
Link5
Link2
CSS
.visited {
color: red;
}
JS
$(document).ready(function() {
// Faking that you already entered the first 2 links
var visited = ['#1', '#2'];
// when clicking it adds the class visited right away
$( "a" ).click(function() {
visited.push($(this).attr('href'));
$(this).addClass( "visited" );
});
// loop trough the visited url and find the corresponding a tags that all have the urls inside the visited variable
$.each(visited, function( index, value ) {
// this gets all links with that same value, if you don't want this you need to store something unique of the a tag or the entire element inside the var visited
var allLinks = $('a[href^="' + value + '"]');
$.each(allLinks, function() {
$(this).addClass( "visited" )
})
// this allert shows you what index and value are
alert( index + ": " + value );
});
});
Hope this helped somehow
convert this line [var links = $(this).attr('href');], to this:
var LINK = $(this),
links = LINK.attr('href');
now, after line $("#visitedLinkContainer").append(visited); put here instead of yours code:
LINK.addClass("visited");
or try this:
$("#rightbox [href='"+links+"']").addClass("visited");
for(var i=0; i<arrayOfLinksAlreadyVisited.length;i++) {
$("#rightbox li a").each(function() {
if($(this).attr("href") == arrayOfLinksAlreadyVisited[i])) {
$(this).addClass("visited");
}
//Match the href with arrayOfLinksAlreadyVisited[i]
//if true then addClass visited to this anchor tag via
//keyword this
// else do nothing
});
}
I hope the above logic will work for you.
I am using following code to show some hidden Bootstrap wells on same pages when a menu item is clicked (works like tabbed content shower). It is working fine, but I want to be able to use it to go to other pages and show a well (based on id attribute there. Its not working that way, please help.
$(document).ready(function()
{
var navItems = $('.menu-level-2 li > a');
var navListItems = $('.menu-level-2 li');
var allWells = $('.menu-level-2-content');
var allWellsExceptFirst = $('.menu-level-2-content:not(:first)');
allWellsExceptFirst.hide();
navItems.click(function(e)
{
e.preventDefault();
navListItems.removeClass('active');
$(this).closest('li').addClass('active');
allWells.hide();
var target = $(this).attr('data-target-id');
$('#' + target).show();
});
});
The question is not fully clear to me, but if you want to go to another page (when clicked on navigation), and on that another page, you want to automatically show that tabbed content, then you should do like this:
navItems.click(function(e)
{
..........
var target = $(this).attr('data-target-id');
window.location='http://example.com/mypage.php#requested_id='+target;
});
and on the target mypage.php, you should have javascript:
$(document).ready(function()
{
if (window.location.hash){
.....
allWells.hide();
$('#' + window.location.hash).show();
}
}
I'm using jQuery hide and show function but I have a problem with the show one.
My javascript code is:
function toggle_visibility(idContent, idLien, question) {
var c = document.getElementById(idContent);
var l = document.getElementById(idLien);
var q = question;
if(c.style.display == 'block') {
$("#" + idContent).hide("blind") ;
l.innerHTML = '<h4><i class=\"icone-rouge icon-right-open-big\"></i>'+ q +'</h4>' ;
}
else {
$("#" + idContent).show("blind") ;
l.innerHTML = '<h4><i class=\"icone-rouge icon-down-open-big\"></i>'+ q +'</h4>' ;
}
}
The problem is that it doesn't work for the hide part when the div is hidden at the load of the page (with display='none'). I can display the block but then I cannot hide it.
I noticed that when I show a content, jQuery delete the display attr in my html style... Maybe there is a link.
Here a link for example : http://jsfiddle.net/29c4D/2/
Thank you.
DescampsAu, since you are using jQuery I rewrote your code to take full advantage of the powerful library. You can see the example in this fiddle.
Let jQuery do the heavy lifting of checking whether an element is hidden or not by making use of either the .toggle() or .slideToggle() methods.
Remove all of the onClick() code within your spans and use this jQuery instead:
jQuery
$(document).ready( function() {
//After the page has loaded, let jQuery know where all of the spans are.
var toggleThis = $(".toggleMe");
//Whenever you click one of the spans do this function.
toggleThis.click( function() {
//Register the span you clicked and the next div that holds the hidden stuffs.
var el = $(this),
nextDiv = el.next(".toggleMeDiv");
//Check if the span's partner div is hidden or showing by checking its css "display" value.
if(nextDiv.css("display") == "block") {
//Change the text of the span to be its title attribute plus whether its partner is showing or hidden.
el.html(el.attr("title")+" hidden");
} else {
el.text(el.attr("title")+" shown");
}
//Let jQuery toggle the partner's visibility.
nextDiv.slideToggle();
});
});
HTML
<span class="toggleMe" title="Quest 1">Quest 1</span>
<div class="toggleMeDiv">Boubou1</div>
<span class="toggleMe" title="Quest 2">Quest 2</span>
<div class="toggleMeDiv">Boubou2</div>
Making this too hard on yourself.
HTML
<span class="toggle" id="lien1" data-original-text="Quest 1">Quest 1</span>
<div id="content1">Boubou1</div>
<span class="toggle" id="lien2" data-original-text="Quest 1">Quest 2</span>
<div id="content2">Boubou2</div>
JS
$(document).ready( function () {
$('.toggle').on('click', function() {
$(this).next('div').toggle('blind', textToggle); // or slideToggle();
});
function textToggle() {
var $target = $(this).prev('span'); // "this" is the div that was toggled.
var originalText = $target.attr('data-original-text');
if ( $(this).is(':visible') ) {
$target.text( originalText + ' open' );
} else {
$target.text( originalText + ' closed' );
}
}
});
A fiddle: http://jsfiddle.net/29c4D/7/
EDIT to include label + effect.
I have a website with 2 links.
Once a user clicks a link, this has to become a h2 title without a link.
When the user clicks on the second link, the first links must be restored to its previous state and the second link should become a h2 element.
The links have the purpose of showing a new tab, so they do not reload the page.
HTML (don't mind the href link)
<div id="Panel" class="header-panels">
<a data-linked="#panelImages" href=".../images/#" tabindex="0" class="active">Foto's</a>
<a data-linked="#panelVideos" href=".../videos/#" tabindex="0">Video's</a>
</div>
Is there anyway to do this with javascript/jquery?
I have tried stuff like:
var p = $('.header-panels .active');
var a = $('<h2></h2>').append(p.contents());
p.replaceWith(a);
And it works to change the a tag into h2, but I cannot seem to recreate the a tag with all the attributes when a users clicks a second time.
Or does anyone know a better approach on this?
Thanks in advance?
Fiddle Demo
var all_a = $('#Panel a'); //cache your selector
var h2 = $('<h2/>').attr('id', 'temp');//created a h2 tag with id temp (just for identification if u need to style it)
all_a.click(function (e) {
e.preventDefault();//stop default behavior of click if u want
all_a.show(); //show all a tag inside id Panel
var $this = $(this); //cache selectore
h2.text($this.text()).insertBefore($this); //insert h2 before current a tag clicked and with it's text
$this.hide(); //hide clicked a
});
.insertBefore()
This script let you toggle 'h2' and 'a' without adding third element, it just replace 'h2' with a 'a' element, and add all the parameters of 'a' element to the 'h2' element on the form of data.
$(document).on('click', '#Panel a', function (e) {
e.preventDefault();
$this = $(this);
var $h2Elem = $this.parents('#Panel').find('h2');
console.log($h2Elem);
$h2Elem.each(function (index, item) {
var linked = $(item).data('linked'),
href = $(item).data('href'),
tabindex = $(item).data('tabindex'),
text = $(item).text();
$(item).replaceWith('<a data-liked="' + linked + '" href="' + href + '" tabindex="' + tabindex + '">' + text + '<a>');
});
var linked = $(this).data('linked'),
href = $(this).attr('href'),
tabindex = $(this).attr('tabindex'),
text = $(this).text();
$this.replaceWith('<h2 data-liked="' + linked + '" data-href="' + href + '" data-tabindex="' + tabindex + '">' + text + '<h2>');
});
Fiddle HERE
why don't you use separate elements and hide/show them as required? E.g.
<div id="Panel" class="header-panels">
<a data-linked="#panelImages" href=".../images/#" tabindex="0" class="active" id="fotolink">Foto's</a><h2 id="foto" style="display: none;">Foto's</h2>
<a data-linked="#panelVideos" href=".../videos/#" tabindex="0" id="videolink">Video's</a><h2 id="video" style="display: none;">Video's</h2>
</div>
<script type="text/javascript">
$("#fotolink").on("click", function (e) {
$("#fotolink").hide();
$("#foto").show();
$("#videolink").show();
$("#video").hide();
//e.preventDefault();
});
$("#videolink").on("click", function (e) {
$("#fotolink").show();
$("#foto").hide();
$("#videolink").hide();
$("#video").show();
//e.preventDefault();
});
</script>
EDIT:
In light of your comment, I would then store the reference to the old anchor element and use detach(). E.g.
var oldLink;
function removeH2() {
var h2 = $("#textheading");
if(h2) {
$(oldLink).insertBefore(h2);
$(h2).remove();
}
}
function toText(a) {
oldLink = a;
var h2 = $('<h2 id="textheading">' + $(a).text() + '</h2>');
$(h2).insertAfter(a);
$(a).detach();
}
$("#fotolink").on("click", function (e) {
//e.preventDefault();
removeH2();
toText(e.target);
});
$("#videolink").on("click", function (e) {
//e.preventDefault();
removeH2();
toText(e.target);
});
I've three div tags in a page.
<div id = '1'>
</div>
<div id = '2'>
</div>
<div id = '3'>
</div>
When a user click on tag, respective div will load,they all will be on one page with one submit button.
Now ,how to validate the div,i've to know which div the user clicked.
update
This is my vaidation script
function x()
{
var x = true;
some validation script
return x;
}
Shed some light here,it will help me to go forward.
Thanks in advance!!
Something like this should do the trick
var lastClickedId;
$('div').click(function()
{
// Use a class to change appearance and track selected
$('div').removeClass('selected');
$(this).addClass('selected');
// Or just track the id in a variable
lastClickedId = $(this).attr('id');
});
function validate()
{
alert('last clicked div ID was: ' + lastClickedId + ' aka: ' + $('div.selected').attr('id'));
}
as i see you used id attribute with a number - its not valid in HTML5.
you can use the id for this . some thing like this
demo : JsFiddle
$('div').click(function()
{
alert('you clicked ' + $(this).attr('id'));
});