Reputation: 740
I'm working on a product page for a store with the ability to preview multiple images. As of right now the current image being viewed updates the # hashtag on the URL. I have a select list with each option that is tagged with a class matching each potential hashtag.
I got a start, but just not quite sure how to use jQuery to take the hashtag, match it with a class and do something. Would it be better to trigger a click or simply update the option to 'selected'?
Here is my start, not quite sure why it's not working.
https://jsfiddle.net/ykmgzyc7/
var url = window.location.href;
var hash = url.substring(url.indexOf('#'));
$('option.' + hash).trigger('click');
Upvotes: 0
Views: 635
Reputation: 8670
You can get the hash using:
(window.location.hash).split("").slice(1).join("")
This gets the hash, converts in a array of chars, removes the fisrt char (#) and converts again to a String. Then you need a event handler for the Hash change event, where you assign the new value:
window.onhashchange = function(){
var value = (window.location.hash).split("").slice(1).join("");
$('#your_select_id').val( value );
};
Your HTML needs to be addapted to something like this, setting the value for each SELECT item:
<ul>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
</ul>
<select id="your_select_id">
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
Upvotes: 0
Reputation: 904
Since you aren't actually loading a new page and just using the anchors you can dynamically modify the selection with jquery.
HTML:
<ul>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
</ul>
<select id="selectOptions">
<option class="one">One</option>
<option class="two">Two</option>
<option class="three">Three</option>
</select>
Jquery:
$("a").on("click",function(){
var link=$(this).attr('href');
var hash = link.substring(link.indexOf('#')+1);
$('#selectOptions option').removeAttr('selected');
$('#selectOptions .'+hash).attr('selected',true);
});
https://jsfiddle.net/ykmgzyc7/3/
Upvotes: 1
Reputation:
var url = window.location.href;
console.log(url);
var hash = url.substring(url.indexOf('#') + 1)
console.log(hash);
$('option.' + hash).trigger('click');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
</ul>
<select>
<option class="one">One</option>
<option class="two">Two</option>
<option class="three">Three</option>
</select>
Upvotes: 0