How to give parameters to a function in object literal patern - javascript

I'm trying to solve my problem with object literal pattern.
Here is my jsFiddle: https://jsfiddle.net/1w8Lcdwk/
I have an accordion and when i select on the first panel the 4 and 5 option in select element it disables me the panel 2 and panel 3. This is working. Now i have to change the button functionality. When a panel is disabled it should go to the next active(not disabled) panel.
How can i this.controllTab(event, $next=3, $previous=3); give the function these parameters without to call the accordion function. The function should be called only when i hit the next button. I'm changing the $next: $previous steps from 1 to 3. But this is not working.
var bestellvorgang = {
$accordion:null,
init: function() {
this.cacheDom();
this.bindEvent();
$accordion.accordion();
},
cacheDom: function() {
$accordion = $('#accordion');
$btnTabControl = $accordion.find('button[name=tab-control]');
$productSelect = $accordion.find('#productSelect');
},
bindEvent: function() {
$btnTabControl.on('click', this.controllTab.bind(this));
$productSelect.on('change', this.productSelect.bind(this));
},
controllTab: function(event, $next=1, $previous=1) {
event.preventDefault();
var delta = $(event.currentTarget).is('.next') ? $next:-$previous;
$accordion.accordion('option', 'active', ($accordion.accordion('option', 'active')) + delta);
},
productSelect: function(event) {
$selected = event.currentTarget.value;
switch($selected) {
case 'p4':
$('#ui-id-3, #ui-id-5').addClass('ui-state-disabled');
this.controllTab(event, $next=3, $previous=3);
break;
case 'p5':
$('#ui-id-3, #ui-id-5').addClass('ui-state-disabled');
break;
default:
$('#ui-id-3, #ui-id-5').removeClass('ui-state-disabled');
}
}
};
$(document).ready(function(){
bestellvorgang.init();
});

Changed
this.controllTab(event, $next=3, $previous=3);
to
this.controllTab(event, 4, 1);
Seems to be working. See here - https://jsfiddle.net/VaTz88/1w8Lcdwk/1/

When a panel is disabled it should go to the next active(not disabled) panel.
Because you change the active panel in:
controllTab: function(event, $next=1, $previous=1) {
it's enough to add at the end a test in order to move to the next active panel if the active one is disabled:
controllTab: function(event, $next=1, $previous=1) {
event.preventDefault();
var delta = $(event.currentTarget).is('.next') ? $next : -$previous;
$accordion.accordion('option', 'active',
($accordion.accordion('option', 'active')) + delta);
var next = 'gt';
var prev = 'lt';
if (event.target.textContent.trim().toLowerCase() == 'previous') {
next = 'lt';
prev = 'gt';
}
var activePanel = $accordion.accordion('option', 'active');
if ($accordion.children('h3.ui-accordion-header')
.eq(activePanel).is('.ui-state-disabled')) {
var x = $accordion.children('h3.ui-accordion-header:not(ui-state-disabled):'
+ next + '(' + activePanel + '):first');
if (x.length == 0) {
x = $accordion.children('h3.ui-accordion-header:not(ui-state-disabled):'
+ prev + '(' + activePanel + '):last');
}
$accordion.accordion('option', 'active', (x.index() > 0) ? x.index() - 1 : x.index());
}
},
var bestellvorgang = {
$accordion: null,
init: function () {
this.cacheDom();
this.bindEvent();
$accordion.accordion();
},
cacheDom: function () {
$accordion = $('#accordion');
$btnTabControl = $accordion.find('button[name=tab-control]');
$productSelect = $accordion.find('#productSelect');
},
bindEvent: function () {
$btnTabControl.on('click', this.controllTab.bind(this));
$productSelect.on('change', this.productSelect.bind(this));
},
controllTab: function(event, $next=1, $previous=1) {
event.preventDefault();
var delta = $(event.currentTarget).is('.next') ? $next : -$previous;
$accordion.accordion('option', 'active', ($accordion.accordion('option', 'active')) + delta);
var next = 'gt';
var prev = 'lt';
if (event.target.textContent.trim().toLowerCase() == 'previous') {
next = 'lt';
prev = 'gt';
}
var activePanel = $accordion.accordion('option', 'active');
if ($accordion.children('h3.ui-accordion-header').eq(activePanel).is('.ui-state-disabled')) {
var x = $accordion.children('h3.ui-accordion-header:not(ui-state-disabled):' + next + '(' + activePanel + '):first');
if (x.length == 0) {
x = $accordion.children('h3.ui-accordion-header:not(ui-state-disabled):' + prev + '(' + activePanel + '):last');
}
$accordion.accordion('option', 'active', (x.index() > 0) ? x.index() - 1 : x.index());
}
},
productSelect: function (event) {
$selected = event.currentTarget.value;
switch ($selected) {
case 'p4':
$('#ui-id-3, #ui-id-5').addClass('ui-state-disabled');
this.controllTab(event, $next=3, $previous=3);
break;
case 'p5':
$('#ui-id-3, #ui-id-5').addClass('ui-state-disabled');
break;
default:
$('#ui-id-3, #ui-id-5').removeClass('ui-state-disabled');
}
}
};
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<div id="accordion">
<h3>Section 1</h3>
<div>
<p>
Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
</p>
<label for="productSelect">Choose a Product:</label>
<select id="productSelect">
<option value="p1">Product 1</option>
<option value="p2">Product 2</option>
<option value="p3">Product 3</option>
<option value="p4">Product 4</option>
<option value="p5">Product 5</option>
</select>
<br><br>
<button type="button" name="tab-control" class="btn btn-success pull-right next">Next <span
class="glyphicon glyphicon-circle-arrow-down" aria-hidden="true"></span></button>
</div>
<h3>Section 2</h3>
<div>
<button type="button" name="tab-control" class="btn btn-info pull-right previous">Previous <span
class="glyphicon glyphicon-circle-arrow-up" aria-hidden="true"></span></button>
<p>
Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
suscipit faucibus urna.
</p>
<button type="button" name="tab-control" class="btn btn-success pull-right next">Next <span
class="glyphicon glyphicon-circle-arrow-down" aria-hidden="true"></span></button>
</div>
<h3>Section 3</h3>
<div>
<button type="button" name="tab-control" class="btn btn-info pull-right previous">Previous <span
class="glyphicon glyphicon-circle-arrow-up" aria-hidden="true"></span></button>
<p>
Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
</p>
<button type="button" name="tab-control" class="btn btn-success pull-right next">Next <span
class="glyphicon glyphicon-circle-arrow-down" aria-hidden="true"></span></button>
</div>
<h3>Section 4</h3>
<div>
<button type="button" name="tab-control" class="btn btn-info pull-right previous">Previous <span
class="glyphicon glyphicon-circle-arrow-up" aria-hidden="true"></span></button>
<p>
Cras dictum. Pellentesque habitant morbi tristique senectus et netus
et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
mauris vel est.
</p>
</div>
</div>

Related

Keep Cookie Consent Banner hidden once Users Accepted Cookies

I've managed to get the cookie consent banner to work, where the cookies aren't set when the page loads. Only once the user clicks on the "Accept" button, the cookies will set and show up within the dev tool Application. Once the "Accept" button has been clicked, the banner is hidden, but only temporarily. Because when I refresh the page, or click on a different page, the cookie consent banner shows up again, even though User has already accepted cookies.
I've tried out a bunch of stuff, and am stuck on how I can keep the banner hidden, after user has accepted the cookies.
Note: I have a custom cookie made and use the Google Tag Manager/Google Analytics cookies.
I would appreciate any help on this! Thank you!
HEAD SCRIPTS
<head>
<!-- Cookie Consent Banner -->
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('consent', 'default', { 'ad_storage': 'denied', 'analytics_storage': 'denied' });
</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=TAG_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'TAG_ID');
</script>
<script>
function consentGranted() {
gtag('consent', 'update', { 'ad_storage': 'granted', 'analytics_storage': 'granted' });};
</script>
<script>
function dismissCookieBanner() {
gtag('consent', 'update', { 'ad_storage': 'denied', 'analytics_storage': 'denied' });};
</script>
<!-- Cookie Consent Banner -->
</head>
HTML
<div role="region" aria-label="cookie-consent-banner" id="cookie-banner">
<div class="cookie-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div class="cookie-buttons">
<button type="button" class="accept-cookies" onclick="consentGranted()">Accept</button>
<button type="button" class="dismiss-cookies" onclick="dismissCookieBanner()">Dismiss</button>
</div>
</div>
JAVASCRIPT
function consentGranted() {
var cookieConsentBanner = $('#cookie-banner');
if ( cookieConsentBanner.length ) {
if ( Cookies.get('CUSTOM_COOKIE') != 'true' ) {
var acceptCookieButton= cookieConsentBanner.find('.cookie-buttons .accept-cookies');
acceptCookieButton.on('click', function() {
Cookies.set( 'CUSTOM_COOKIE', 'true', { expires: 365 } );
cookieConsentBanner.remove();
});
};
};
};
function dismissCookieBanner() {
var cookieConsentBanner = $('#cookie-banner');
var dismissCookieBanner= cookieConsentBanner.find('.cookie-buttons .dismiss-cookies');
dismissCookieBanner.on('click', function() {
cookieConsentBanner.remove();
});
};
I would recommend using localStorage to store the cookie consent data, and then once the page loads, put the banner onscreen if no answer was given, else, not place it. Example:
function consentGranted() {
localStorage.setItem('consent', true)
var cookieConsentBanner = $('#cookie-banner');
if ( cookieConsentBanner.length ) {
if ( Cookies.get('CUSTOM_COOKIE') != 'true' ) {
var acceptCookieButton= cookieConsentBanner.find('.cookie-buttons .accept-cookies');
acceptCookieButton.on('click', function() {
Cookies.set( 'CUSTOM_COOKIE', 'true', { expires: 365 } );
cookieConsentBanner.remove();
});
};
};
};
function dismissCookieBanner() {
localStorage.setItem('consent', false)
var cookieConsentBanner = $('#cookie-banner');
var dismissCookieBanner= cookieConsentBanner.find('.cookie-buttons .dismiss-cookies');
dismissCookieBanner.on('click', function() {
cookieConsentBanner.remove();
});
};
document.getElementById('cookie-banner').hidden = localStorage.getItem('consent') != null
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
<!-- Cookie Consent Banner -->
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('consent', 'default', { 'ad_storage': 'denied', 'analytics_storage': 'denied' });
</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=TAG_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'TAG_ID');
</script>
<script>
function consentGranted() {
gtag('consent', 'update', { 'ad_storage': 'granted', 'analytics_storage': 'granted' });};
</script>
<script>
function dismissCookieBanner() {
gtag('consent', 'update', { 'ad_storage': 'denied', 'analytics_storage': 'denied' });};
</script>
<!-- Cookie Consent Banner -->
</head>
<h1>My site</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dui vivamus arcu felis bibendum ut tristique et egestas quis. Nunc consequat interdum varius sit amet. Ac odio tempor orci dapibus. Eu consequat ac felis donec et odio pellentesque diam. Faucibus nisl tincidunt eget nullam. Aenean et tortor at risus viverra adipiscing at in. Lacinia at quis risus sed vulputate odio ut enim. Sagittis eu volutpat odio facilisis mauris sit amet massa. Maecenas volutpat blandit aliquam etiam erat velit scelerisque. Vitae tempus quam pellentesque nec nam. Vitae proin sagittis nisl rhoncus mattis rhoncus urna.
</p>
<div role="region" aria-label="cookie-consent-banner" id="cookie-banner">
<div class="cookie-text">Do you accept the cookie policy?</div>
<div class="cookie-buttons">
<button type="button" class="accept-cookies" onclick="consentGranted()">Accept</button>
<button type="button" class="dismiss-cookies" onclick="dismissCookieBanner()">Dismiss</button>
</div>
</div>
JSFiddle

Multiple event handlers only firing on first element, not the target

So I am trying to make a more/less content toggle feature, it worked just fine until I started adding more boxes to be toggled. I read up on using multiple event handlers and the suggestion was to use document.getElementsByClassName(); and iterate through them, but the second button when clicked does not show/hide the correct content, only the first one.
Any help is appreciated. The simpler way would be to use jQuery or assign different IDs to the buttons and call the function on each one but I'm sure it must be possible to just create/call the event listener once and have it work on every subsequently added element.
Here is my code:
HTML
<div class="card">
<div class="cardLessContent">
<h1>Here is a card</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent auctor mi sollicitudin, tristique tortor eget, tempus elit. Vestibulum ante leo, aliquam ac dapibus at, auctor vitae ligula.</p>
</div>
<div id="cardMoreContent" class="cardMoreContent">
<p> Nam finibus nec augue at semper. Quisque sit amet ex eu augue rutrum aliquet. Suspendisse dui enim, gravida quis turpis a, auctor pellentesque velit.</p>
</div>
<button id="toggleContent" class="toggleContent toggledOff">More</button>
</div>
<div class="card">
<div class="cardLessContent">
<h1>Here is a card</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent auctor mi sollicitudin, tristique tortor eget, tempus elit. Vestibulum ante leo, aliquam ac dapibus at, auctor vitae ligula.</p>
</div>
<div id="cardMoreContent" class="cardMoreContent">
<p> Nam finibus nec augue at semper. Quisque sit amet ex eu augue rutrum aliquet. Suspendisse dui enim, gravida quis turpis a, auctor pellentesque velit.</p>
</div>
<button id="toggleContent" class="toggleContent toggledOff">More</button>
</div>
JavaScript
const btnToggleContent = document.getElementsByClassName("toggleContent");
const cardMoreContent = document.getElementById("cardMoreContent");
var toggleContent = function() {
cardMoreContent.classList.toggle("showing");
this.classList.toggle("toggledOff");
if(this.classList.contains("toggledOff")) {
this.innerHTML = "More";
}
else {
this.innerHTML = "Less";
}
}
for (var i = 0; i < btnToggleContent.length; i++) {
btnToggleContent[i].addEventListener("click", toggleContent);
}
JSFiddle: https://jsfiddle.net/jw3qe9xf/6/
Id attribute should be unique in HTML.Otherwise it will only pick the first occurence of that Id.In your case you will always toggle the first cardMoreContent
Here is a simple solution for you by using event.target
Javascript
const btnToggleContent = document.getElementsByClassName("toggleContent");
const cardMoreContent = document.getElementById("cardMoreContent");
var toggleContent = function(e) {
e.target.previousElementSibling.classList.toggle("showing");
this.classList.toggle("toggledOff");
if(this.classList.contains("toggledOff")) {
this.innerHTML = "More";
}
else {
this.innerHTML = "Less";
}
}
for (var i = 0; i < btnToggleContent.length; i++) {
btnToggleContent[i].addEventListener("click", toggleContent);
}
JSFiddle : https://jsfiddle.net/c1gdjk25/
Yes , works only for first. This is reason :
you have multiply use ' id="toggleContent" ' same id value for more than one element it is wrong in basic.
Id attribute must be uniq !
Use example from this answer :
How to get child element by class name?
You will need only childNodes and loop trow it.
Count on that you can search child from child element also ...
after you remove all ids attributes change your javascript code to :
const btnToggleContent = document.getElementsByClassName("toggleContent");
var toggleContent = function(e) {
/*e.target will get the clicked element which is the button clicked and parentElement
gives you the parent element of this button which is the card you want to modify*/
var card = e.target.parentElement;
/*when you have the card you can use on its getElementsByClassName to retreive all
elements that have the class (cardMoreContent) in this case theres only one so you take
the first element from the array returned with [0]*/
var cardMoreContent = card.getElementsByClassName("cardMoreContent")[0];
//then rest of the code stays the same
cardMoreContent.classList.toggle("showing");
if(this.classList.contains("toggledOff")) {
this.innerHTML = "More";
}
else {
this.innerHTML = "Less";
}
}
for (var i = 0; i < btnToggleContent.length; i++) {
btnToggleContent[i].addEventListener("click", toggleContent);
}

Load html page for this tabbed angularjs page

I found this jsfiddle sample code which is provides multiple tabs for a single angularjs webapge.
http://jsfiddle.net/helpme128/99z393hn/
I adapted it to my own code. I wanted a certain tab to load a certain webpage my-custom-page.html.
Here are my relevant code. The html code;
<div id="tabs" ng-controller="StkViewMainCtrl">
<ul>
<li ng-repeat="tab in tabs"
ng-class="{active:isActiveTab(tab.url)}"
ng-click="onClickTab(tab)">{{tab.title}}
</li>
</ul>
<div id="mainView">
<div ng-include="currentTab"></div>
</div>
</div>
<script type="text/ng-template" id="one.tpl.html">
<div id="viewOne">
<h1>View One</h1>
<p>Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim
congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc.</p>
</div>
</script>
<script type="text/ng-template" id="my-custom-page.html">
<div id="viewTwo">
<h1>View Two</h1>
<p>Curabitur vulputate, ligula lacinia scelerisque tempor, lacus lacus ornare ante, ac egestas est urna sit
amet arcu. Class aptent taciti sociosqu.</p>
</div>
</script>
The controller code;
.controller('StkViewMainCtrl', ['$scope', 'configuration',
function ($scope, $configuration) {
$scope.tabs = [{
title: 'One',
url: 'one.tpl.html'
}, {
title: 'Two',
url: 'my-custom-page.html'
}, {
title: 'Three',
url: 'three.tpl.html'
}];
$scope.currentTab = 'one.tpl.html';
$scope.onClickTab = function (tab) {
$scope.currentTab = tab.url;
}
$scope.isActiveTab = function(tabUrl) {
return tabUrl == $scope.currentTab;
}
}]);
No effect took place. my-custom-page.html does not load. my-custom-page.html is on the same folder as the single webpage that is being run.
Html is loading from main page, so if you want to load html from another html file in folder you should use something like ng-include.
So try to change
<script type="text/ng-template" id="my-custom-page.html">
<div id="viewTwo">
<h1>View Two</h1>
<p>Curabitur vulputate, ligula lacinia scelerisque tempor, lacus lacus ornare ante, ac egestas est urna sit
amet arcu. Class aptent taciti sociosqu.</p>
</div>
to
<script type="text/ng-template" id="my-custom-page.html">
<div id="viewTwo" ng-include="my-custom-page.html"></div>
i changed a code and here is a new code on plunker

add value to existing class in jQuery

First of all, I have searched quite some hours to find this.. I presume it has an easy fix but I'm really new to jQuery and Javascript, so I'm here for your help.
The problem
I'm working with multiple divs and jQuery ToggleSlide(). I want the script to find the right div to open when I click the corresponding div.
For example, when I click the div 'hackandfly', I want it to open the div 'hackandfly-open'.
The code
$(document).ready(function() {
$('.project-open').hide();
$('.hackandfly, .scanergy, .connecting-food').click(function() {
$slidah = $(this);
$slidah.slideToggle();
$('div.project-open').not($slidah).slideUp();
});
});
HTML
<div class="content projects">
<h3>Projects</h3>
<div class="project project-big hackandfly">
<h3>Hack and Fly</h3>
</div>
<div class="hackandfly-open project-open" style="display: none;">
<img src="images/schiphol-logo.png" class="img-project-open"> Proin nec elit ac sapien facilisis ultrices. Integer pellentesque ex a luctus fringilla. Aenean in quam quam. Integer gravida quam eget mauris laoreet hendrerit. Vestibulum feugiat ipsum id.
<br>
<br>
Metus aliquet iaculis. Proin massa justo, maximus in tortor et, Proin massa justo, maximus in tortor et. In aliquam laoreet magna et iaculis. Vestibulum vel orci lobortis, elementum nulla eget, porta eros. Interdum et malesuada fames ac ante ipsum primis in faucibus.
<br>
<br>
Proin massa justo, maximus in tortor et, tincidunt efficitur nibh. Mauris vulputate euismod lorem, vel rutrum ipsum iaculis eu.
</div>
So what I'm looking for, is that when I push 'hackandfly' div, 'scanergy' div or the 'connecting-food' div, I want it to slideToggle the corresponding div that has -open behind it (I have 3 divs with info called hackandfly-open, scanergy-open, connecting-food-open).
I tried some things like:
$slidah = $(this).after('-open');
And some other stuff but it didn't work. Who can help me?
Cheers!
Use attr() like
$(document).ready(function() {
$('.project-open').hide();
$('.hackandfly, .scanergy, .connecting-food').click(function() {
$slidah = $($(this).attr('class')+'-open');
$slidah.slideToggle();
$('div.project-open').not($slidah).slideUp();
});
});
However, the above will fail if you have multiple classes.
A workaround would be to add data-* to the clicked elements like
<div class="hackandfly other-class" data-class-target="hackandfly-open"></div>
and then
$(document).ready(function() {
$('.project-open').hide();
$('.hackandfly, .scanergy, .connecting-food').click(function() {
$slidah = $('.'+$(this).attr('data-class-target'));
$slidah.slideToggle();
$('div.project-open').not($slidah).slideUp();
});
});
I would generate a unique click handler for each class. That way, you can store all the applicable class names in an array:
// Creates a new unique click function for each class name
function generateClickHandler(className) {
return function(e) {
// select the open class here
$slidah = $('.'+className+'-open');
$slidah.slideToggle();
$('div.project-open').not($slidah).slideUp();
};
}
// Iterate over all the class names and add a new function for each
var clsList = ["hackandfly", "scanergy", "connecting-food"];
$.each(clsList, function(className) {
$("."+className).click(generateClickHandler(className));
});
Use:
$('.hackandfly, .scanergy, .connecting-food').click(function() {
$slidah = $("."+$(this).attr('class')+"-open");
$slidah.slideToggle();
});
If you added a wrapper around each section like so:
<div class="content projects">
<h3>Projects</h3>
<div class="project-wrapper">
<div class="project project-big hackandfly">
<h3>Hack and Fly</h3>
</div>
<div class="hackandfly-open project-open" style="display: none;">
{...}
</div>
</div>
</div>
you could use parent and find to get the corresponding element as follows:
$('.hackandfly, .scanergy, .connecting-food').click(function() {
$(this).parent().find('.project-open').eq(0).slideToggle();
}

JavaScript error, syntax ok

I have a problem with the following JS, at some point no longer works.
from "$.each" no longer works
How can I fix? there seems to be a problem in taking the class
Can anyone help me? I can not understand where is the problem, even if I create two js file does not work ..
Html output
<ol id="AjaxTimeline">
<ul class="timeline">
<li class="timeline-inverted">
<div class="timeline-badge primary">
<a><i class="glyphicon glyphicon-record" rel="tooltip" title="11 hours ago via Twitter" id=""></i></a>
</div>
<div class="timeline-panel">
<div class="timeline-heading">
<div class="caption">
<img class="img-responsive" src="http://lorempixel.com/1600/500/sports/2">
</div>
<div class="timeline-body">
<p>Suspendisse id felis mi. Quisque blandit mattis nisl eu volutpat. Duis viverra lacus quis arcu mattis ac varius ligula convallis. Maecenas magna enim, molestie ac ultrices sed, convallis vel dolor. Vestibulum sed hendrerit massa. Integer consequat odio vitae est rutrum et egestas nibh sodales. Sed adipiscing nisl vel massa bibendum molestie.</p>
</div>
<div class="timeline-footer">
<div class="voto_class" id="1">
<div class="voto_btn">
<div class="voto_positivo_btn"> </div>
<span class="voto_positivo_s">0</span>
</div>
<div class="voto_btn">
<div class="voto_negativo_btn"> </div>
<span class="voto_negativo_s">0</span>
</div>
</div>
<a><i class="glyphicon glyphicon-share"></i></a>
<a class="pull-right">Continua a leggere</a>
</div>
</div>
</div>
</li>
</ul>
</ol>
JavaScript:
$(document).ready(function() {
var base_caricamento = 0;
var loading = false;
var news_caricate = 5;
$('#AjaxTimeline').load("Caricamento_n.php", {
'gruppo_0':base_caricamento
}, function() {
base_caricamento++;
});
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height())
{
if(base_caricamento <= news_caricate && loading==false)
{
loading = true;
$('.caricamento_ajax').show();
$.post('Caricamento_n.php',{
'gruppo_0': base_caricamento
}, function(data){
$("#AjaxTimeline").append(data);
$('.caricamento_ajax').hide();
base_caricamento++;
loading = false;
}).fail(function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
$('.caricamento_ajax').hide();
loading = false;
});
}
}
});
$.each( $('.voto_class'), function(){
var unique_id = $(this).attr("id");
post_data = {'unique_id':unique_id, 'vote':'fetch'};
$.post('Voti.php', post_data, function(response) {
$('#'+unique_id+' .voto_positivo_s').text(response.vote_up);
$('#'+unique_id+' .voto_negativo_s').text(response.vote_down);
},'json');
});
$(".voto_class .voto_btn").click(function (e) {
var clicked_button = $(this).children().attr('class');
var unique_id = $(this).parent().attr("id");
if(clicked_button==='voto_negativo_btn')
{
alert("OK");
}
else if(clicked_button==='voto_positivo_btn')
{
alert("Error");
}
});});
The problem lies in tag <ol id="AjaxTimeline">. I do not understand why, but if I delete the script works tag

Categories

Resources