1
I’m trying to create a Jquery plugin but I can’t adapt a . each into a . append, how can I use it to work inside the . append?
Follow my example below:
var selectBox = $('.select__atual');
var selectOption = $('.select__opcoes__label');
selectBox.click(function(){
$(this).toggleClass('open');
$('.select__opcoes').toggle();
});
selectOption.click(function(){
var selectName = $(this).text();
$('.select__atual__text').text(selectName);
});
jQuery.fn.customSelect = function(options){
var settings = $.extend({
border : '1px solid red',
list : ['Option 1', 'Option 2'],
defaultText : 'Choose an option'
}, options);
return this.each(function(){
console.log(settings.list);
$(this)
.append(`<div class="wrapper-select">
<div class="select__atual">
<span class="select__atual__text">${settings.defaultText}</span>
</div>
<div class="select__opcoes">${settings.list}</div>
</div>`)
.css('border', settings.border);
});
}
$('#mySelect').customSelect({
border: '1px solid #cecece',
defaultText: 'Escolha uma opção',
});
*{
box-sizing:border-box;
}
main{
width:600px;
display:flex;
margin:0 auto;
}
.wrapper-select{
position:relative;
width:100%;
}
.wrapper-select input{
display:none;
}
.select__atual{
height:50px;
width:100%;
cursor:pointer;
border:1px solid;
border-color: #cecece;
display:flex;
align-items:center;
padding:0 15px;
}
.select__atual.open{
border-bottom:none;
}
.select__opcoes{
width:100%;
display:none;
border:1px solid;
border-top:none;
border-color:#cecece;
}
.select__opcoes__label{
display:flex;
height:50px;
width:100%;
align-items:center;
padding:0 15px;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<div id="mySelect"></div>
</main>
you have to put the arguments in your callback function,
this.each(function(idx, element){ ... })
and then use that element inside theeach
.– guijob
@guijob I tried to do this but it seems that it does not recognize the arguments from within the Settings
– haykou