1

I have a bit of coding that displays div's when requested through a link, now I want to be able to link to that page, and execute the JavaScript with the parameter given through the url in PHP.

The JavaScript displays and closes div's when requested through links.

Link example:

<a href="#div1" class="selectType">Click here for div1</a>
<a href="#div2" class="selectType">Click here for div2</a>
<a href="#div3" class="selectType">Click here for div3</a>

JavaScript code:

$('.selectType').on('click', function(e){
    e.preventDefault();
    var targetDiv = $($(this).attr('href'));
    if(!targetDiv.is(':visible')){
        $('.hide').slideUp();
        targetDiv.slideDown();
    }else{
        $('.hide').slideUp();
    }
});

css for div:

.hide{display:none;}

div code:

<div id="div1" class="hide">Text in div1</div>
<div id="div2" class="hide">Text in div2</div>
<div id="div3" class="hide">Text in div3</div>

I want to give the URL a link like so:

http://www.example.com/pages/index.php?pageid=div2

When that page is visited, the JavaScript will execute as if the link "Click here for div2" was pressed, so that div2 pops up.

I have no idea where to get started, as in, I do know how to grab the $_GET['pageid'] variable, but no clue how to combine it with the JavaScript into displaying the requested div.

Thanks ahead!

BananaMan
  • 168
  • 1
  • 10
  • Set an active class in the HTML based on the querystring, and write your javascript around that. You know using querystrings instead of hashes will reload the page when the anchors are clicked ? – adeneo Apr 19 '14 at 20:08
  • How would I go about doing that? My JavaScript is horrible, let alone jQuery :p – BananaMan Apr 19 '14 at 20:19

1 Answers1

0

First change your hide/show into a function to save repeating code... ie:

var toggleSelectType = function(target) {
    var targetDiv = $(target);

    if (!targetDiv.is(':visible')) {
        $('.hide').slideUp();
        targetDiv.slideDown();
    } else {
        $('.hide').slideUp();
    }
};

$('.selectType').on('click', function(e){
    e.preventDefault();
    toggleSelectType($(this).attr('href'));
});

Add a function that helps you grab query string values such as: (How can I get query string values in JavaScript?) ** credit

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, " "));
}

Then when the page loads check for the value of pageid and run your function:

var pageId = getParameterByName('pageid');
toggleSelectType('#'+pageId);
Community
  • 1
  • 1
Joey Cadle
  • 188
  • 1
  • 3
  • 11