jQuery pagination kills my toggle switches - ajax

My page shows posts stored in my Database through a loop. Each post is paired with a like and dislike button. The page has two master controls switches that show/hide all liked posts and show/hide all dislike posts.
This all works perfectly. I am now trying to paginate said posts while still keeping the above functions intact. This is proving difficult. In short, if I click on a div with class "like" var value is set to "1" and ajax fires, storing that value in my database and returns a success message. The same happens for dislike with the difference being that var value is set to "0".
If the user chooses to hide all liked posts, they do indeed hide but no other posts pop up in their places. I'd like it for the pagination to ALWAYS display X results per page even after some posts get toggled. As it is, If I hide 3 of 5 posts, only 2 posts remain instead of having 3 next posts come in.
imtech_pager.js looks for a div called "contained" and looks inside it for all divs with class "z". These divs then get paginated. This does work. It's just that it causes the above problem.
likedislike.js (toggling x number of posts doesn't result in pulling in the next x number of posts):
$(document).ready(function() {
likestatus = 1;
dislikestatus = 1;
$(document).on("click", ".like", function(){
postID = $(this).attr('id').replace('like_', '');
// Declare variables
value = '1';
myajax();
return false;
});
$(document).on("click", ".dislike", function(){
postID = $(this).attr('id').replace('dislike_', '');
// Declare variables
value = '0';
myajax();
return false;
});
function myajax(){
// Send values to database
$.ajax({
url: 'check.php',
//check.php receives the values sent to it and stores them in the database
type: 'POST',
data: 'postID=' + postID + '&value=' + value,
success: function(result) {
$('#Message_' + postID).html('').html(result).prependTo('#post_' + postID);
if (result.indexOf("No") < 0){ //If return doesn't contain string "No", do this
if (value == 1){ //If post is liked, do this
$('#post_' + postID).removeClass('dislike').addClass('like');
$('#dislikebtn_' + postID).removeClass('dislikeimgon').addClass('dislikeimgoff');
$('#likebtn_' + postID).removeClass('likeimgoff').addClass('likeimgon');
// If Hide Liked checkbox is on, toggle the post
if (likestatus % 2 == 0) {
$('#post_' + postID).toggle();
}
} else if (value == 0){ //If post is disliked, do this
$('#post_' + postID).removeClass('like').addClass('dislike');
$('#likebtn_' + postID).removeClass('likeimgon').addClass('likeimgoff');
$('#dislikebtn_' + postID).removeClass('dislikeimgoff').addClass('dislikeimgon');
// If Hide Disliked checkbox is on, toggle the post
if (dislikestatus % 2 == 0) {
$('#post_' + postID).toggle();
}
}
}
}
});
}
//When Hide Liked checkbox clicked, toggle all Liked posts.
$('#show_likes').on('click', function() {
countlikes = $('[id^=post_].like').length;
if (countlikes >0) {
likestatus++;
$('[id^=post_].like').toggle();
if (likestatus % 2 == 0) {
$('#hidelikedbtn').removeClass('hidelikedimgoff').addClass('hidelikedimgon');
} else {
$('#hidelikedbtn').removeClass('hidelikedimgon').addClass('hidelikedimgoff');
}
}
return false;
});
//When Hide Disliked checkbox clicked, toggle all Disliked posts.
$('#show_dislikes').on('click', function() {
countdislikes = $('[id^=post_].dislike').length;
if (countdislikes >0) {
dislikestatus++;
$('[id^=post_].dislike').toggle();
if (dislikestatus % 2 == 0) {
$('#hidedislikedbtn').removeClass('hidedislikedimgoff').addClass('hidedislikedimgon');
} else {
$('#hidedislikedbtn').removeClass('hidedislikedimgon').addClass('hidedislikedimgoff');
}
}
return false;
});
});
imtech_pager.js (this paginates all divs with class "z" - works fine)
var Imtech = {};
Imtech.Pager = function() {
this.paragraphsPerPage = 3;
this.currentPage = 1;
this.pagingControlsContainer = '#pagingControls';
this.pagingContainerPath = '#contained';
this.numPages = function() {
var numPages = 0;
if (this.paragraphs != null && this.paragraphsPerPage != null) {
numPages = Math.ceil(this.paragraphs.length / this.paragraphsPerPage);
}
return numPages;
};
this.showPage = function(page) {
this.currentPage = page;
var html = '';
this.paragraphs.slice((page-1) * this.paragraphsPerPage,
((page-1)*this.paragraphsPerPage) + this.paragraphsPerPage).each(function() {
html += '<div>' + $(this).html() + '</div>';
});
$(this.pagingContainerPath).html(html);
renderControls(this.pagingControlsContainer, this.currentPage, this.numPages());
}
var renderControls = function(container, currentPage, numPages) {
var pagingControls = 'Page: <ul>';
for (var i = 1; i <= numPages; i++) {
if (i != currentPage) {
pagingControls += '<li>' + i + '</li>';
} else {
pagingControls += '<li>' + i + '</li>';
}
}
pagingControls += '</ul>';
$(container).html(pagingControls);
}
}
index.php (displays all the divs and buttons)
<div id="content">
<div id="mastercontrols">
<div id="show_likes" style="position:absolute;">
<a id="hidelikedbtn" class="hidelikedimgoff" href="#"><span></span></a>
</div>
<div id="show_dislikes" style="position:absolute; right: 0em;">
<a id="hidedislikedbtn" class="hidedislikedimgoff" href="#"><span></span></a>
</div>
</div>
<div id="contained">
<?php
$data = mysql_query("SELECT * FROM Posts") or die(mysql_error());
while($row = mysql_fetch_array( $data )){
?>
<div class="z">
<div id="post_<?php echo $row['postID']; ?>" class="post">
<div id="post_<?php echo $row['postID']; ?>_inside" class="inside">
<div id="like_<?php echo $row['postID']; ?>" class="like" style="position:absolute; right: 2.5em;">
<a id="likebtn_<?php echo $row['postID']; ?>" class="likeimgoff" href="#"><span></span></a>
</div>
<div id="dislike_<?php echo $row['postID']; ?>" class="dislike" style="position:absolute; right: 0em;">
<a id="dislikebtn_<?php echo $row['postID']; ?>" class="dislikeimgoff" href="#"><span></span></a>
</div>
<b><?php echo $row['Title']; ?></b><br>
<?php echo $row['Description']; ?><br>
<div id="postleft">
</div>
<div id="postright">
</div>
</div>
</div>
<div id="Message_<?php echo $row['postID']; ?>" class="reminder"></div>
</div>
<?php
}
?>
</div>
<div id="pagingControls"></div>
</div>
<script type="text/javascript">
var pager = new Imtech.Pager();
$(document).ready(function() {
pager.paragraphsPerPage = 5; // set amount elements per page
pager.pagingContainer = $('#container'); // set of main container
pager.paragraphs = $('div.z', pager.pagingContainer); // set of required containers
pager.showPage(1);
});
</script>
So any ideas? This perplexes me to no end! The variables are all different, everything formats properly. The divs do get paginated and the pagination buttons (page 1, 2, 3, etc) all work. There's just something inside imtech_pager.js that stops the rest of my code from working as it should.
Again:
Toggling some posts does not result in repopulating the paginated pages. (Hiding 3 of 5 posts results in leaving 2 posts on the page instead of bringing in the next 3 posts for a total of 5 posts on the page).

I think the issue is probably that the elements are being added and removed from the DOM which is then making them lose their handlers. You should be able to just delegate the events.
Since you are using 1.7, I believe the syntax would be:
$(document).on("click", ".dislike", function(){
instead of
$('.dislike').on('click', function() {
This is the equivilent to live pre-1.7. You can refine the delegation for better performance by replacing document with a more specific selector which is the parent of all of the elements you are trying to attach the handler to, but which is not being added and removed.

Related

How to make an id= from an XML call give a link to what its calling?

One of my API calls gives a youtube link and I want the link to be clickable and open on another tab, but nothing is working
this is mode code HTML:
//the id produces a youtube link that that can be clicked, but if I add the id to the href, then it wont work.
<a href="" target="_blank">
<p id="strYoutube2"></p>
</a>
my js code:
//this is my XML call, if theres another .link function other than .innerXML for the youtube link, maybe that can be the issue, but I cant find anything online.
function getPosts() {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.themealdb.com/api/json/v1/1/random.php', true);
console.log(xhr.readyState);
xhr.send();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
let response = JSON.parse(xhr.responseText);
console.log('response below:')
console.log(response);
console.log(response.meals[0].strMealThumb);
document.getElementById('strMeal').innerText = response.meals[0].strMeal
document.getElementById('strCategory').innerText = response.meals[0].strCategory
document.getElementById('strArea').innerText = response.meals[0].strArea
document.getElementById('strTags').innerText = response.meals[0].strTags
document.getElementById('strYoutube').innerHTML = response.meals[0].strYoutube
document.getElementById('strMealThumb').src = response.meals[0].strMealThumb
}
}
}
The HTML element with id strYoutube does NOT exist in you provided code:
document.getElementById('strYoutube').innerHTML = response.meals[0].strYoutube
For achieve what you're triyng to do, you can change your code as follows:
Check that I set an img HTML element with a predefined width and height.
Check the working jsfiddle here too:
// This is your function for get the posts of the given API URL.
function getPosts() {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.themealdb.com/api/json/v1/1/random.php', true);
console.log(xhr.readyState);
xhr.send();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
let response = JSON.parse(xhr.responseText);
console.log('response below:')
console.log(response);
console.log(response.meals[0].strMealThumb);
// Comented due these HTML elements aren't here.
//document.getElementById('strMeal').innerText = response.meals[0].strMeal
//document.getElementById('strCategory').innerText = response.meals[0].strCategory
//document.getElementById('strArea').innerText = response.meals[0].strArea
//document.getElementById('strTags').innerText = response.meals[0].strTags
//document.getElementById('strYoutube').innerHTML = response.meals[0].strYoutube
//document.getElementById('strMealThumb').src = response.meals[0].strMealThumb
// Here I set the values to your HTML elements:
// "strYoutube" is the HTML anchor element "<a href>".
document.getElementById('strYoutube').href = response.meals[0].strYoutube;
// "myImg" is the HTML image element "<img src>".
document.getElementById('myImg').src = "https://www.themealdb.com/images/media/meals/ysqupp1511640538.jpg";
document.getElementById('myImg').alt = response.meals[0].strMeal;
document.getElementById('myImg').title = response.meals[0].strMeal;
}
}
}
// Call your function and set the values ion the HTML elements:
getPosts();
<a href="" target="_blank" id="strYoutube">
<p id="strYoutube2">
<img src="#" id="myImg" alt="image" title="" style="width: 150px; height: 150px;" />
</p>
</a>

Suggenstion on focusout function

What I'm trying to accomplish? :
I have provided a search bar, if you type something it will autosuggest you the results. By clicking on the results user will be taken to the reference page. I wanna provide a functionality that if a user clicks outside the result or input box, the result will get disappeared.
What did it take? :
Html, css, js, php and ajax
Problem? :
I am able to see the results but I have problem with focusout function in jquery. ( I don't know much about jquery ) If I click on the body of my webpage, the result element doesn't get disappeared.
Half success! :
Well I tried focusout and focusin function on input box, the result element was able to get disappeared but then if I click on any list-item (results) it stopped taking me to the reference page since I used focusout with input box
jquery:
$(document).ready(function(){
$('#search_bar_input').focusin(function(){
$('#results').css('display','block') ;
});
} );
$(document).ready(function(){
$('#search_bar_input').focusout(function() {
$(this).val('') ;
$('#results').css('display','none') ;
} );
} );
Html :
<form id="search_bar" name="search">
<input type="text" placeholder="Search a Song or Artist..." name="search_text" onkeyup="findMatch()" id="search_bar_input"/>
</form>
<div id="results">
</div>
Ajax or something I don't know to be honest. :
function findMatch() {
var xmlhttp ;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest() ;
} else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") ;
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML = xmlhttp.responseText ;
}
}
xmlhttp.open('GET', 'include/search.php?search_text='+document.search.search_text.value, true) ;
xmlhttp.send() ;
}
I have a file search.php here is the code
<?php
if(isset($_GET['search_text']) ) {
$search_text = $_GET['search_text'] ;
}
if(!empty($search_text)) {
if(mysql_connect('localhost', 'root', '' ) ) {
if(mysql_select_db('getthetrack.com')) {
$query = "SELECT `Artists` FROM `artist's name` WHERE `Artists` LIKE '".mysql_real_escape_string($search_text)."%' ";
$query_run = mysql_query($query) ;
if(mysql_num_rows($query_run)){
while($query_row = mysql_fetch_assoc($query_run)) {
echo '<ul class="search_results">';
$Artists = '<li class="search_results_items">'.$query_row['Artists'].'</li>' ;
echo ''.$Artists.'' ;
echo '</ul>';
}
} else {echo "No results found!";}
}
}
}
Any suggestions on the functionality I wanna deliver?
You can try this:
$( "#search_bar_input" ).blur(function() {
});
Try this so:
$(document).click(function (e)
{
var container = $("#results");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});

Adding two newsletter form in homepage - magento

i am using two newsletter form like the below link
http://www.astleyclarke.com/uk/jewellery-care
One is using mouse over function the email subscriber is popping up
and second 1 at the bottom. If I comment on any one of the forms then the other 1 is working fine.
Could any 1 help me solve this, or may have done with this.
below is the code for header.phtml
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('a.login-window').click(function() {
// Getting the variable's value from a link
var loginBox = jQuery(this).attr('href');
//Fade in the Popup and add close button
jQuery(loginBox).fadeIn(300);
//Set the center alignment padding + border
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
jQuery(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
jQuery('body').append('<div id="mask"></div>');
jQuery('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
jQuery('a.close, #mask').live('click', function() {
jQuery('#mask , .login-popup').fadeOut(300 , function() {
jQuery('#mask').remove();
});
return false;
});
});
</script>
<div id="login-box" class="login-popup">
<img src="close_pop.png" class="btn_close" title="Close Window" alt="Close" />
<?php echo $this->getLayout()->createBlock('newsletter/subscribe')->setTemplate('newsletter/subscribe.phtml')->toHtml(); ?>
</div>
for footer.phtml
<?php echo $this->getLayout()->createBlock('newsletter/subscribe')->setTemplate('newsletter/subscribe.phtml')->toHtml(); ?>

how to implement onpopstate? confused after reading so many things

I am loading content using AJAX, and changing URL by using pushastate, below is my code, can anybody tell me how to implement onpopstate to enable back button in my case.
HTML
<div id="tabs" style="margin:1px 0px 0px 15px;">
<ul class="tabs-ul">
<li id="boardLi" class="current-tab"><a class="current-tab" href="board.jsp">Board</a></li>
<li id="aboutLi">Info</li>
<li id="photoLi">Photo Albums</li>
</ul>
</div>
JS
$(document).ready(function() {
function loadContent(path,c,pageName){
$.ajax({ url: path, success: function(html) {
$('#ajax-content').empty().append(html);
window.history.pushState({path:''},'',pageName+'?tab='+c);
}
});
}
function checkC(target){
var c='';
if(target=='aboutme.jsp')
{c='info';}
else if(target=='board.jsp')
{c='board';}
else if(target=='photo.jsp')
{c='photo';}
else if(target=='tab.jsp')
{c='ht';}
return c;
}
$(".tabs-ul li a").on('click', function(e) {
e.preventDefault();
$('#ajax-content').empty().append("<div id='loading'><img src='images/preloader.gif' alt='Loading' /></div>");
$('.tabs-ul li a').removeClass('current-tab');
$('.tabs-ul li').removeClass('current-tab');
$(this).addClass('current-tab');
$(this).parent().addClass('current-tab');
var url = window.location.pathname;
var pageName = url.substring(url.lastIndexOf('/') + 1);
var target=$(this).attr('href');
var c=checkC(target);
loadContent(target,c,pageName);
return false;
});
var loaded = false;
window.onpopstate = function(e) {
if (!loaded) {
loaded = true;
return;
} else {
alert(window.loacation.back().pathname);
loadContent();
}
};
});
When user clicks on link, first of all I am adding removing class for loading then I am getting URL and getting the page name from that URL(saved in 'pageName'), 'target' is href attr of clicked link and 'c' is the value I will be showing in url(for example, example.com/profile.jsp?tab=info, here if the href is info.jsp then 'c' would be info), finally I am calling 'loadContent' function which loads ajax content and changes URL using pushState.

Inline editing with AJAX - how do I create multiple editable areas on the same page?

I found a tutorial on how to create editable regions on a page using AJAX.
This is great, except it was written for a single element with a unique ID. I'd like to be able to click on multiple elements on the same page and have them also be editable (e.g., I'd like to alter the script below so it works not with a single element, but with multiple elements of a particular class).
Here is my HTML:
<h2>Edit This</h2>
<p class="edit">This is some editable content</p>
<p class="edit">This is some more editable content</p>
<p class="edit">I could do this all day</p>
Here is the JS file I'm working with (I updated the script per Rex's answer below): This script is, unfortunately, not working - can anyone point me in the right direction?
Event.observe(window, 'load', init, false);
function init() {
makeEditable('edit');
}
function makeEditable(className) {
var editElements = document.getElementsByClassName(className);
for(var i=0;i<editElements.length;i++) {
Event.observe(editElements[i], 'click', function(){edit($(className))}, false);
Event.observe(editElements[i], 'mouseover', function(){showAsEditable($(className))}, false);
Event.observe(editElements[i], 'mouseout', function(){showAsEditable($(className), true)}, false);
}
}
function showAsEditable(obj, clear) {
if (!clear) {
Element.addClassName(obj, 'editable');
} else {
Element.removeClassName(obj, 'editable');
}
}
function edit(obj) {
Element.hide(obj);
var textarea ='<div id="' + obj.id + '_editor"><textarea cols="60" rows="4" name="' + obj.id + '" id="' + obj.id + '_edit">' + obj.innerHTML + '</textarea>';
var button = '<input type="button" value="SAVE" id="' + obj.id + '_save"/> OR <input type="button" value="CANCEL" id="' + obj.id + '_cancel"/></div>';
new Insertion.After(obj, textarea+button);
Event.observe(obj.id+'_save', 'click', function(){saveChanges(obj)}, false);
Event.observe(obj.id+'_cancel', 'click', function(){cleanUp(obj)}, false);
}
function cleanUp(obj, keepEditable) {
Element.remove(obj.id+'_editor');
Element.show(obj);
if (!keepEditable) showAsEditable(obj, true);
}
function saveChanges(obj) {
var new_content = escape($F(obj.id+'_edit'));
obj.preUpdate = obj.innerHTML // stow contents prior to saving in case of an error
obj.innerHTML = "Saving…";
cleanUp(obj, true);
var success = function(t){editComplete(t, obj);}
var failure = function(t){editFailed(t, obj);}
var url = 'http://portal.3roadsmedia.com/scripts/edit.php';
var pars = 'id=' + obj.id + '&content=' + new_content + '&pre=' + obj.preUpdate;
var myAjax = new Ajax.Request(url, {method:'post',
postBody:pars, onSuccess:success, onFailure:failure});
}
function editComplete(t, obj) {
obj.innerHTML = t.responseText;
showAsEditable(obj, true);
}
function editFailed(t, obj) {
obj.innerHTML = 'Sorry, the update failed.';
cleanUp(obj);
}
The Event.observe method currently attaches to a single element with the ID specified. You should change this to iterate over a collection of elements located by classname and attach to each of them. According to the Prototype documentation, you can provide an element object as the first parameter, instead of an ID.
Currently, id is a string:
function makeEditable(id) {
Event.observe(id, 'click', function(){edit($(id))}, false);
//...
Which means Event.observe is attaching to the click event of the element with the ID provided. You want to attach to all elements with a class. Try:
function makeEditable(className) {
var editElements = document.getElementsByClassName(className);
for(var i=0;i<editElements.length;i++) {
Event.observe(editElements[i], 'click', function()
//...
}
//...

Resources