How to make Object in jQuery - javascript

I'm trying to show ul on click. I can do it with simple jQuery but I would like to use the oop way. Please correct me if I'm wrong thanks!
HTML
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" id="toggleDropdown">
<i class="icon-envelope"></i>
</a>
<ul style="display:none;" id="dropdown">
<li>No new messages are available</li>
</ul>
</li>
jQuery
(function(){
var dropdowns = {
dropDownContainer: $('#toggleDropdown'),
dropDown : $('#dropdown'),
init:function(){
$(dropDownContainer).click(function(){
dropDown.show(200);
})
}
};
dropdowns.init();
})();

The thought is not wrong, your implementation is poor. You see, referencing properties or methods from you class. You should use this to create instant references inside your constructor .
Here is a simple example to start with:
(function () {
var testOOP = {
container: $('a'),
init: function (e) {
this.container.click(function (e) {
e.preventDefault();
alert(1)
})
}
};
testOOP.init();
})();
https://jsfiddle.net/jeatqLLe/1/

You don't have access to dropDown or dropDownContainer at that point; use $('#dropdown') and $('#dropDownContainer') in the init function.

I think you got it almost correct. Use "this" to refer your objects properties as follows.
(function(){
var dropdowns = {
dropDownContainer: $('#toggleDropdown'),
dropDown : $('#dropdown'),
init:function(){
$(this.dropDownContainer).click(function(){
this.dropDown.show(200);
})
}
};
dropdowns.init();
})();

Related

Bootstrap4 scroll spy - active to parent li

I've got bootstrap4 menu like this:
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="nav-link" href="#introduction">INTRODUKTION <span class="sr-only">(current)</span></a></li>
</ul>
Default scroll spy adds active to nav-link (a) I need to change this, becouse my active should be after nav-item (li). Can I do that ?
You can see this here:
Example
When I click, everything goes ok - but on scroll - active is a href.
By default .active class will be added to only anchor tags.
Try something like this for your requirement
$('[data-spy="scroll"]').on('activate.bs.scrollspy', function () {
$(".navbar-nav .active").removeClass("active").parent().addClass("active");
})
Add attribute data-spy="scroll"
on <div class="container"> the parent of section with id="introduction"
like
<div class="container" data-spy="scroll">
I found solution. I need just to add new event (cssClassChanged) - and working !
(function(){
// Your base, I'm in it!
var originalAddClassMethod = jQuery.fn.addClass;
jQuery.fn.addClass = function(){
// Execute the original method.
var result = originalAddClassMethod.apply( this, arguments );
// trigger a custom event
jQuery(this).trigger('cssClassChanged');
// return the original result
return result;
}
})();
and then
$(".nav-link").bind('cssClassChanged' , function(e) {
$(".nav-item").each( function() {
if( $(this).hasClass("active") == true ) {
$(this).removeClass("active");
}
});
$(this).removeClass("active").parent().addClass("active");
});

Not able to find data-id when selecting element

Apologies in advance I feel as if this is a very simple solution and I am in the middle of a severe brain fart. I am simply trying to grab the data-id of an item I am clicking using ES6 syntax but no matter which way I run it I keep getting undefined.
HTML
<ul>
<li class="list-item" data-id="item-1">Click me</li>
<li class="list-item" data-id="item-2">Click me</li>
<li class="list-item" data-id="item-3">Click me</li>
</ul>
JS
let $el = $('ul');
class List {
constructor($el) {
this.$el = $el;
this.$listItem = $el.find('li');
this.attachHandlers();
}
attachHandlers() {
this.$listItem.on('click', () => {
var data = $(this).attr('data-id');
console.log(data);
});
}
}
const _init = () => {
if ($el.length) {
$el.each((i, v) => {
new List($(v));
});
}
};
_init();
Ive simplified the code down as much as possible, anybody see what I am doing wrong here?
The problem is in your attachHandlers method. Since you are using an arrow function, this refers to the class and not the element that was clicked.
Change the arrow function to a regular function.
In addition to Josan's answer, if you want to continue using the arrow function, use it like this:
class List {
constructor($el) {
this.$el = $el;
this.attachHandlers();
}
attachHandlers() {
this.$el.on('click', 'li', (e) => {
var data = $(e.currentTarget).attr('data-id');
console.log(data);
});
}
}
For more discussion, refer to this thread.
Simpler and easier by just using JQuery:
$(".list-item").on('click', function() {
console.log($(this).data('id'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="list-item" data-id="item-1">Click me</li>
<li class="list-item" data-id="item-2">Click me</li>
<li class="list-item" data-id="item-3">Click me</li>
</ul>

Finding the text inside this element

I'm looking to make a fairly simple operation: you click on an li, you get the text inside, using JavaScript (not JQuery). What I can't figure out (or find out) is how to get the innerHTML.
function enable() {
document.addEventListener('click', e => {
if (e.target.classList.contains('refine-menu-li')) {
var selected = this.innerHTML;
console.log('stuff'); // Working
console.log(selected); // Not working
}
});
}
Is the problem that I am using class and so require a for-loop? Or is this a foolish thing to try and use?
Thanks!
You could try something like this, without using an arrow function:
document.getElementById("js-list")
.addEventListener("click",function(e) {
if(e.target && e.target.nodeName == "LI") {
console.log(e.target.innerHTML);
}
});
<ul id="js-list">
<li>value1</li>
<li>value2</li>
<li>value3</li>
</ul>
Arrow functions capture this from the context they are declared in.
this.innerHTML is not the innerHTML you are looking for.
You probably want e.target.innerHTML.
If you weren't using an arrow function, then this will wouldn't be the value you wanted. Event handlers are called in the context of the element they are bound to (document in this case), not the element that triggered the event.
Try this
function enable() {
document.addEventListener('click', e => {
var current = e.target;
if (e.target.classList.contains('refine-menu-li')) {
var selected = current.innerHTML;
console.log('stuff'); // Working
console.log(selected); // Not working
}
});
}
enable();
<ul>
<li class='refine-menu-li a'>1 </li>
<li class='refine-menu-li b '>2</li>
<li class='refine-menu-li c '>3</li>
<li class='refine-menu-li d'>4</li>
</ul>

jquery ui sortable - sort by attribute value

If I'm running jquery ui and using sortable in a ul element:
$("#example").sortable({
update: function () {
//do something
}
});
<ul id="example">
<li data-ex="1.1"></li>
<li data-ex="0.1"></li>
<li data-ex="1.4"></li>
</ul>
Is there a way to trigger an event that sorts my elements by the data attribute on the fly? Essentially I'd like a button that sorts the li elements by the data attribute also also triggers the update in sortable().
You can try this:
$(document).ready(function () {
$("#example").sortable({//Sortable initialisation
update: function () {
updatehandler();//Custom function which handles sortable update.
}
});
$('a').click(function () {// Click handler to sort
var list = $('#example');
var listItems = list.find('li').sort(function (a, b) {
return $(a).attr('data-ex') - $(b).attr('data-ex');
});
list.find('li').remove();
list.append(listItems);
updatehandler();//Call updatehandler after sorting
return false;
});
});
function updatehandler() {
//Your update handler code.
alert('updated');
}
HTML:
Sort
<ul id="example">
<li data-ex="1.1">1.1</li>
<li data-ex="0.1">0.1</li>
<li data-ex="1.4">1.4</li>
</ul>
Demo : http://jsfiddle.net/lotusgodkk/GCu2D/151/
I'm not too familiar with sortable, but this fiddle shows how you can get the data-ex attribute's value, and define a variable to use for sorting in the plugin:
http://jsfiddle.net/FF7z6/
I added class="sort" to your html, and then we get the value by using the following:
var dataEx;
$('.sort').click(function(){
var dataEx = $(this).attr("data-ex");
alert(dataEx);
});

javascript toggle visibility and add function preventDefault

i´m trying to display popup-divs within a site and it works quite well, except for one thing –
i want to prevent the Default behavior of refreshing the site. I´m new to javascript and i honestly don´t know how to add the function (i already found the right one, i think...).
<script type="text/javascript">
function toggleVisibility(selectedPopup) {
var popvar = document.getElementsByClassName('popup');
for(var i=0; i<popvar.length; i++) {
if(popvar[i].id == selectedPopup) {
popvar[i].style.visibility = 'visible';
} else {
popvar[i].style.visibility = 'hidden';
}
}
}
It works like i wanted it to work – it displays the selected DIV, hides the other and vice versa.
Still, i want to prevent the site from jumping to the top. So i added this snippet:
$(function() {
$("#").click(function(event){
event.preventDefault()
});
});
The responding html is this:
<a href="#" onclick="toggleVisibility('pop01');">
and this
<div id="pop01" class="popup">
<img src="assets/img/01/01_02_pop_01.png"></img>
</div>
How can i include the second javascript snippet into the first one?
Many thanks in advance...
You should just be able to pass event into your function.
The HTML
<a href="#" onclick="toggleVisibility(event, 'pop01');">
The Javascript (partial)
function toggleVisibility(event, selectedPopup) {
event.preventDefault();
var popvar = document.getElementsByClassName('popup');
// etc...
}
I believe that should do it!
JSFiddle Example: http://jsfiddle.net/c4LXf/
As an alternative you can just remove the # and replace with javascript:;
<a href="javascript:;" onclick="toggleVisibility('pop01');">
Or remove the onclick and just use the href:
<a href="javascript:toggleVisibility('pop01');">
Instead of
$(function() {
$("#").click(function(event){
event.preventDefault()
});
try
$(function() {
$("#").click(function(event){
return false;
});
You can just use following:
<a href="#" onclick="return toggleVisibility('pop01');">
If you add a return false in your function:
function toggleVisibility(selectedPopup) {
// your code ...
return false;
}
Or, Change your link like:
<a href="javascript:toggleVisibility('pop01');">

Categories

Resources