How to make those dynamic anchor links with jQuery? - javascript

I've recently discovered a website which does something really cool! Example:
There are two links "Cat" and "Dog".
There are two DIV containers, id="catImage" and id="dogImage"
The initial URL looks like http://mysite.com/#cat
Initially, the cat image is visible
Clicking on the Dog link will fade out the catImage div and fade in the dogImage div
Additionally, it will change the anchor in the browser URL to: http://mysite.com/#dog
Opening the website with httü://mysite.com/#dog will show the dog image initially
Is this possible using jQuery? How would I scan for that anchor, and how would I call a function when the link is clicked without causing the link to follow some URL? I'm an objective-c dude and don't know anything about JS... hope my question isn't too dumb for you.

with this markup:
<div id="images">
<div id="catImage">some cat image here</div>
<div id="dogImage" style="display:none;">some dog image here</div>
</div>
<div id="anchors">
catImage anchor
dogImage anchor
</div>
and with this js (assuming jquery 1.4.x)
$(function () {
$("#anchors a").click(function () {
// send the index of the anchor to the function
fadeImage($(this).index());
});
var hash = window.location.hash;
if (hash) {
var elementId = "#" + hash.substring(1) + 'Image';
var $div = $(elementId);
// check if this element exists, and if so, send that index to the function
if ($div.length) {
fadeImage($div.index());
}
}
});
function fadeImage(index) {
$("#images div:eq(" + index + ")").fadeIn().siblings().fadeOut();
}
And to explain what's going on here:
I'm using the jquery index() function to get the index of the element relative to its siblings. I then pass that index to the fadeImage function, which finds the same index div and fades it in. By using chaining, I then look to the siblings of that div to fade them out. This is useful if you have more than 2 divs to fade out here.
For the anchor/hash usage, I just find the div with the matching id and get its index, and pass it to the same function.
jQuery docs can explain the various methods much better than I can.

Using location.href you can get the full URL in javascript.
you can substring or string replace your domain name and rest will be your parameter dog or cat.
When you have the parameter .
jquery functions like show(); hide (); to show cat and hide dog.
By adding or removing style also you can change images
.add() is there
addClass removeClass is there
http://mattwhite.me/11tmr.nsf/D6Plinks/MWHE-695L9Z
http://rockmanx.wordpress.com/2008/10/03/get-url-parameters-using-javascript/
http://api.jquery.com/show/
http://api.jquery.com/addClass/

Update: Oh I forgot, obviously you should read a tutorial about jQuery if you want to use it.
You can get and set the hash of the URL via window.location.hash, e.g.
alert(window.location.hash);
//and
window.location.hash = 'test'
You should read about events in order to fully understand how it works. The event object provides a preventDefault() method, which is exactly doing what it says (preventing the default behavior).
E.g. with jQuery:
$('a').click(function(e) {
//Do something..
// prevent to follow the link
e.preventDefault();
});

Related

Append string to every url on page load

I have my website in English but want to show it in Spanish when page loads. So, I got a script from Google Translate that I put in my header file but I need to append some #googtrans(en|fr) at the end of every URL. What I've done so far is:
$(document).ready(function () {
$('a').each(function () {
this.href += '#googtrans(en|es)';
})
});
But a problem with this code is, it is blocking my popups and bootstrap dropdowns.
Is there any simple way to put that trailing string to every URL on page load.
Filter out links that have attributes or classes you don't want the hash applied to:
For example:
$('a').not('[data-toggle], [href^="#"]').prop('hash','#googtrans(en|es)');
If selectors in not() aren't enough you can use the more robust filter() method
A more ideal approach would be being able to have classes on your <a> to represent the ones you do want modified.
<a class="translate">
$('a.translate').prop('hash','#googtrans(en|es)');
OR
<div class="translate">
<a>
</div>
$('.translate a').prop('hash','#googtrans(en|es)');
Note that using the hash property achieves the same as concatenating href
Without seeing more of your html it is hard to provide a lot more help
Now you replace with this code all <a> tags.
Best way - it's taking Google Translator block links on other div, like this:
<div id="gtr">
...
</div>
And Script:
$(document).ready(function () {
$('#gtr a').each(function () {
$(this).attr('href', $(this).attr('href')+'#googtrans(en|es)');
});
});
Instead of
this.href += “#googtrans(en|es)”;
Try this:
$(this).attr("href", $(this).attr("href") + "#googtrans(en|es)");

How to remove a class via JavaScript (NOT jQuery) at Wordpress

I need your help at a problem of my Wordpress Webpage. My Wordpress-page is an Single-Page-App with 3 different boxes of content. The left and center boxes are static, the right one changes its content by clicking on links of the other boxes. I decided, to load all the content in the right box and show them with the CSS-command visibility. With a combination of pathJS and JS, i want the URL to change by clicking on the links. So far so good - all works fine, but i dont get managed via my JS-Function to remove the shown-class.
My script looks like this:
<script>
function showDetailContent(showid) {
//suche objekt right_id -> was du zeigen willst -> getelementbyid
alert("1");
var id = document.getElementsByClassName('shown');
alert("2");
id.classList.remove('shown');
alert("3");
document.getElementByID("right_" + showid).classList.add('shown');
alert("4");
}
//var c = document.getElementById('content'); -->do the function :)
Path.map("#/?p=<?php the_id();?>").to(function () {
showDetailContent(<?php the_id();?>);
});
Path.listen();
</script>
The alerts are just my way of "debugging". I think its not the best way to debugg, but i am very new in the world of prorgamming and this is kind of easy.
However, the first two alerts are shown, if i activate a link. So the (first) mistake is on the line
id.classList.remove('shown');
Normally, the right-box is hidden, so that only one content is load.
Do you understand my problem till here?
I would appreciate fast help!
Greetings, Yannic! :)
Look at this : http://snipplr.com/view/3561/ to know remove class pure javascript
getElementsByClassName gets multiple elements, try:
var id = document.getElementsByClassName('shown')[0];
Or iterate through them if you want to remove class from all elements with class shown;

Text captions on multiple Images with jQuery

I'm new to jQuery so please be patient. I want to create a text caption that slides down on an image when you hover over a link on the page. I can do this when there's just one image with one caption but I have several images with different captions on one page.
I would like to create one function that can handle all of these in seperate instances and not create a function for each image/textcaption. The reason being is that the images and text is dynamic and changing in quantity overtime.
Please see an example of the code below, the .portText is a class of about 7 instances, when I hover over .moreInfo the text for every image slides down. I understand why this is happening, and I think I need to use ($this) somehow, but I also think i need to connect the picture to the text differently that it's done here. Hope this makes sense. Can anyone help? Cheers!
$(function() {
$('.moreInfo').hover(
function() {
$('.portText').slideDown('slow');
},
function() {
$('.portText').slideUp('slow');
}
)
});
You can refer to the element that was hovered over using $(this).
The way I usually do this is to make portText a child of the moreInfo div:
<div class="moreInfo">
<div class="portText">
....
</div>
</div>
Then instead of just $('.portText') you can do $('.portText', this) (i.e. all portTexts that are children of the hovered element).
Edit: Another way to do it would be to use the data attribute and give each portText an ID:
<div class="moreInfo" data-id="1">....</div>
<div class="portText" id="portText-1">...</div>
Then for Javascript:
$('.moreInfo').hover(
function() {
var myId= "#portText-" + $(this).data('id');
$(myId).slideDown('slow');
},
function() {
var myId= "#portText-" + $(this).data('id');
$(myId).slideUp('slow');
}
);

How to add jquery events to added classes?

I am trying to create an image gallery, I am using numbers instead of left/right arrows. At the moment, I am trying to get it working with only 2 image (i.g 2 numbers)
this is the html . the id page, is the highlighted number
<div class="grid_1 pagelink" id="page"><p>1</p></div>
<div class="grid_1 pagelink"><p>2</p></div>
the first time the page loads, the code below works. so when I click on link 2 the the code bellow runs fine. But then I want the same code to be triggered when I click back on the first link; but when I do that, the page refreshes by ignoring the code bellow:
$('.pagelink').live('click', function(e){
e.preventDefault();
var frame = $(this).text() - 1;
var frames = 240 * frame;
// $('#gal').animate({marginLeft:'500px'},'slow');
$('#gal').animate({marginLeft: "+="+frames+'px'},'slow');
$(this).attr('id', 'page').removeClass('pagelink');
$('#page').addClass('pagelink').removeAttr('id','page');
// $('#book').animate({ left: '50' });
})
I thought that the .live() would do that for me but it is not working.
I hope you could help
thank you
Previous, this is because you are removing the class of link "pagelink" which were used to map the clicked event.
Also, use another class instead of id(#page) to identify the #page link, id might be problem if its already assign to other link. like
$(this).removeClass('pagelink').addClass('page');
$('.page').addClass('pagelink').removeClass('page');
live should work fine. i think you have a bug in your code, and its probably here:
$(this).attr('id', 'page').removeClass('pagelink');
$('#page').addClass('pagelink').removeAttr('id','page');
what exactly are you trying to accomplish with this code?
when you click on page2, the you set the div's id to be page, but now you have 2 elements with an id of page, and when you select that id, you get the first one (ie page1), but you still remove the class pagelink from page2
in other words, the bug is that at some point you will have 2 elements with the same id (and ids must be unique btw) so when you select that id with $('#page') you always get the first one

Getting my head around jQuery

OK, I'm designing a site and thought I'd stick some jQuery in as I really need so js experience.
Page with my problem is here: http://new.focalpix.co.uk/moreinfo.php
JS in question is:
$(document).ready(function(){
$(".answer").css("display","none");
$("#maincontent a.animate").click(function() {
$("#maincontent .answer").slideUp('slow');
var id = $(this).attr('href');
$(id).slideDown('slow');
return false;
});
});
This works fine, but if you click on a link where the answer has already slid down, then it slides up, then back down again.
I'm not sure on the cleanest way to stop this happening - any ideas?
You should be using the .slideToggle() effect.
$(document).ready(function() {
$(".answer").css("display","none");
$("#maincontent a.animate").click(function() {
$("#maincontent .answer").slideToggle('slow');
});
});
First, I'd suggest the following structure for your faq's:
<div id="faq">
<div class="qa" id="faq_greenandflies">
<span class="q">What is green and flies</span>
<div class="a">
Super Pickle!
</div>
</div>
<div class="qa" id="faq_redandbadforteeth">
<span class="q">What is Red and bad for your teeth</span>
<div class="a">
a Brick
</div>
</div>
<!--
More FAQ's here
-->
</div>
and then defining your jQuery as follows:
<script type="text/javascript">
$(function(){
// hide all answers
$('div#faq .qa .a').hide();
// bind a click event to all questions
$('div#faq .qa .q a').bind(
'click',
function(e){
// roll up all of the other answers (See Ex.1)
$(this).parents('.qa').siblings().children('.a').slideUp();
// reveal this answer (See Ex.2)
$(this).parents('.qa').children('.a').slideDown();
// return true to keep any other click events
return true;
});
// check location.hash to see if we need to expand one (direct link)
$(location.hash).find('.q a').click();
});
</script>
Explanation:
(Ex.1)
this is the link that was clicked
get the element that contains this and has a class of 'qa' (the box that contains both question and answer)
select all of its siblings. (we now have all qa's as a jQ object)
hide the answers
(Ex.2)
this is the line or link that was clicked
get the element that contains this and has a class of 'qa' (the box that contains both question and answer)
reveal the answer
A working demo is here.
This does several things for you:
If a user deep-links to an answer, the answer is automatically revealed
If a user clicks on one answer, all other answers are hidden
You can give your divs proper ids, so which helps search engine optimization of links to individual answers
Use slideToggle() like Soviut said, but just as a tip -- you can declare the display property in the actual CSS file instead of declaring it inside the javascript. jQuery will pick up on the fact that it is hidden in the stylesheet and still perform the appropriate slide function.
You can also use $(".answer").hide();
Instead of setting the display CSS property. Just thought I would let you know.
try using the one method, something like:
$(selector).one('effect', 'data for effect', callback function);
it makes sure an effect only happens once per element.

Categories