1

I'm trying to switch back and forth between two different modes in my website. One mode is "Grid" and the other is "List". So in the url it would be www.example.com/index.php?mode=grid and when you click on a specific link it would change the mode to list. My code only takes it from index.php to one of the queries once;

The Javascript:

    function gridclick(){
        if(location.href.match(/\?mode=/)){
            var reExp = /mode=\d+/;
            var url = window.location.toString();
            var newUrl = url.replace(reExp, "mode=" + "grid");
        }
        else{


    window.location="index.php?mode=grid";
    }
}

function listclick(){
    if(location.href.match(/\?mode=/)){
        var reExp = /mode=\d+/;
        var url = window.location.toString();
        var newUrl = url.replace(reExp, "mode=" + "list");
    }
    else{
        window.location="index.php?mode=list";
    }
}

The HTML:

<img src="images/grid.png" width="18" height="18" alt="Grid view" onClick="gridclick()"/> 
<img src="images/list.png" alt="List view" width="18" height="18" onClick="listclick()"/>
2
  • 1
    Shouldn't you do something with newUrl? Commented Aug 30, 2013 at 23:17
  • Yea, you're right @Jeffman. I added window.location = newUrl; to both but it wont change after being clicked the second time. Commented Aug 30, 2013 at 23:29

1 Answer 1

1

Use location.search to toggle the query parameter and refresh the page. It will also minimize your javascript a ton, see below:

function gridclick(){
    location.search = "mode=grid";
}

function listclick(){
  location.search = "mode=list";
}

UPDATE:

Actually to make it even more efficient I'd modify your code to the following..

HTML:

<img src="images/grid.png" width="18" height="18" alt="Grid view" onClick="toggleView('grid')"/> 
<img src="images/list.png" alt="List view" width="18" height="18" onClick="toggleView('list')"/>

And just have one function handling your view toggle.

Javascript:

function toggleView(view){
  location.search = "mode=" + view;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh wow, I didn't think it could be that simple. Thank you. How do I have this so it doesn't replace all other queries?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.