JacksonDavis JacksonDavis - 4 months ago 11
jQuery Question

Triggering Javascript from a link on a previous page

I have a list of links on a services page that when clicked, reveal content relevant to the individual service. This is to save space on the page. I have done this using slide in JS.

On the homepage I also have a list of services that I would like to have linked the services page and then open up the relevant content dependant on service clicked on the homepage.

I'm a new user of Javascript so unfortunately this isn't something I could work out myself or find a solution for elsewhere. I would really appreciate somebody helping me to find a way of doing this.

Find below a short example of my code:

Homepage

<ul id='homepage-services-list'>
<li><a href='services.php'>Service 1</a></li>
<li><a href='services.php'>Service 2</a></li>
</ul>


Services

<ul class='services-tabs'>

<li class='services-tab'>
<a class='service-1-trigger'>
<div>
<h3>Service 1</h3>
<img src='images/down-arrow-icon.png'>
</div>
</a>
</li>

<article class='service-1-content'>
<p>Content about service etc.</p>
</article>

<li class='services-tab'>
<a class='service-2-trigger'>
<div>
<h3>Service 2</h3>
<img src='images/down-arrow-icon.png'>
</div>
</a>
</li>

<article class='service-2-content'>
<p>Content about service etc.</p>
</article>

</ul>


Javascript - JQuery

$(document).ready(function(){

$(".service-1-trigger").click(function(){

$(".service-1-content").slideToggle(600, function(){
$(this).toggleClass("service-1-toggle").css('display',' ');
});
});

$(".service-2-trigger").click(function(){

$(".service-2-content").slideToggle(600, function(){
$(this).toggleClass("service-2-toggle").css('display',' ');
});
});

});


Thank you!

Answer

You can add anchors to your links.

<ul id='homepage-services-list'>
   <li><a href='services.php#1'>Service 1</a></li>
   <li><a href='services.php#2'>Service 2</a></li>
</ul>

With these anchors, you can extract from the URL the service wanted (1 or 2) and simulate a click with jQuery.

In your document.ready :

var url = document.location.toString();
if (url.indexOf('#') != -1) {
    var num_service =  url.split('#')[1];
    $(".service-" + num_service + "-trigger").click();
} 
Comments