I have a <select>
menu similar to example below:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
On some websites, I've seen that this menu can be triggered via an external image or div.
I've searched on google but almost all questions and answers are related to how to list images inside a select, which is not what I need. I want select menu to appear when a DIV or an image is clicked.
How can I trigger this select menu via a click to another DOM element, i.e., a div?
PS. My website already has jQuery included.
Here I coded a script on JSFiddle to easily select different options from a dropdown by using external divs.
HTML:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<nav>
<div data-value="volvo">volvo</div>
<div data-value="saab">saab</div>
<div data-value="mercedes">mercedes</div>
<div data-value="audi">audi</div>
</nav>
CSS:
select {
display:block;
margin:0 0 10px;
}
div {
padding:5px 10px;
margin:0 0 5px;
border:solid 1px #ccc;
background:#eee;
cursor:pointer;
}
JS:
$(document).ready(function(){
var select = $("select"),
value = "";
$("div").on("click",function(){
value = $(this).attr("data-value"); // Store the value of the clicked div
select.find('option[value="'+ value +'"]') // Match the option with the value we get before
.prop("selected",true) // Assign it selected attr
.end() // Go back to the select
.trigger("change"); // Trigger the change to see the change reflected on the select
});
});
Based on this script, you could increment a lot the functionalities by adding for example urls to each option (ex: data-link="http://google.com") and window.location it on change, or anything you want to.
Anyway if you want a really kick-ass plugin to make it automatically I propose the msDropdown (Documentation here).
This plugin ables you to create custom selects with images, descriptions and many other features by simple bind them with a select tag or with json information. Hope is what you were looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With