Changing text and class with jquery - javascript

I've been stuck all day on a project I'm working on. All funcitonality is there, I'm just having trouble with the jquery, can someone help me out?
here is a visual of the application:
Pretty simple, when I click "like post" a function is called via ajax to run a update to the count on the database, also the same when I press "Dislike"
My problem is with the JQuery, I can't seem to figure out how to make it so when "Like post" is clicked, it is changed to "Already Liked" and the "Already Disliked" changed to "Dislike"
CSS Classes:
"Like Post" = fa fa-thumbs-up like_btn
"Dislike Post" = fa fa-thumbs-down dislike_btn
"Already Liked" = fa fa-check like_btn
"Already Disliked" = fa fa-check fa-check-dislike dislike_btn"
Here is the current JQuery, I've tried a few different things but nothing seems to be working, any suggestions I greatly appreciate.
$('.fa-thumbs-up').click(function() {
var annid = $(this).attr('id');
update_likes(annid, 'like');
//code goes here
});
$('.fa-thumbs-down').click(function() {
var annid = $(this).attr('id');
update_likes(annid, 'dislike');
//code goes here
});
UPDATED JFIDDLE: http://jsfiddle.net/T9wvL/2/

It's easier to toggle elements than to swap text, so I modified your HTML a bit.
http://jsfiddle.net/isherwood/T9wvL/8
.hide {
display: none;
}
<article>
<div class="updates updates-like">
<i class="fa fa-thumbs-up like_btn" id="like">
<span>Like Post</span>
<span class="hide">Already liked</span>
</i>
</div>
<div class="updates updates-dislike">
<i class="fa fa-thumbs-down dislike_btn" id="dislike">
<span>No Good</span>
<span class="hide">Already disliked</span>
</i>
</div>
</article>
$('.updates').click(function () {
$(this).find('i').toggleClass('fa-thumbs-up fa-thumbs-down')
.find('span').toggleClass('hide');
});

HTML:
<article>
<div class="updates-like">
<i class="fa fa-thumbs-up like_btn" id="<? echo $update->annid; ?>">
<span>Like Post </span>
</i>
</div>
<div class="updates-dislike">
<i class="fa fa-thumbs-down dislike_btn" id="<?echo $update->annid;?>">
<span>No Good</span>
</i>
</div>
</article>
JQuery:
$('.like_btn').click(function () {
/*This here runs the update function on the DB.. Not Important
var annid = $(this).attr('id');
update_likes(annid, 'like');*/
//Code here to change "Like Post" to "already Liked" ON CLICK, and to change "already disliked" back to "No Good"
if ( $(this).hasClass('fa-thumbs-up') ) {
$(this).removeClass('fa-thumbs-up')
.addClass('fa-check')
.find('span')
.text('Already Liked');
if ( $('.dislike_btn').hasClass('fa-check fa-check-dislike') ) {
$('.dislike_btn').removeClass('fa-check fa-check-dislike')
.addClass('fa-thumbs-down')
.find('span')
.text('No Good');
}
}
return true;
});
$('.dislike_btn').click(function () {
/*This here runs the update function on the DB.. Not Important
var annid = $(this).attr('id');
update_likes(annid, 'dislike'); */
//Code here to change "No Good" to "already disliked" ON CLICK, and to change "already Liked" back to "No Like Post"
if ( $(this).hasClass('fa-thumbs-down') ) {
$(this).removeClass('fa-thumbs-down')
.addClass('fa-check fa-check-dislike')
.find('span')
.text('Already Disliked');
if ( $('.like_btn').hasClass('fa-check') ) {
$('.like_btn').removeClass('fa-check')
.addClass('fa-thumbs-up')
.find('span')
.text('Like Post');
}
}
return true;
});
Here is the JSFiddle that should work for what you need. I tried to optimize a little bit your code, but I hope it still works fine.

Related

Jquery click function for a second time do not works

when user click for a second time click do not work, user need to reload the page again to it works
<script>
$(document).ready(function() {
$("#like_post").click(function(e) {
// $("#like_post").on("click", "#like_post", function (e) {
e.preventDefault();
var post_info = $("#post_info :input").serialize();
$.post("backend/ajax/like_post.php", post_info).done(function(data) {
$("#like_post").html(data);
$("#like").load(location.href+" #like>*","");
}).fail(function() {
//alert("Error submitting forms!");
})
})
})
</script>
this is the backend return from db
if user liked it will show
<div id="like_post><a href="" id="l"><input type="hidden" value="unlike" name="like_button" /><i style="color:red" class="fa fa-heart fa-2x" aria-hidden="true" data-toggle="tooltip" data-placement="top" title="'.$lang['you_liked_it'].'"></i>
</a></div>
else it will show
<div id="like_post"> <a href="" id="l"><input type="hidden" value="like" name="like_button" /><i class="fa fa-heart-o fa-2x" aria-hidden="true" data-toggle="tooltip" data-placement="top" title="'.$lang['like_it'].'"></i>
</a></div>
the same validation is on frontend where is will change the hidden input to like, or unlike , my backend check is fine and returning all ok when I check the html response, but the problem is that jquery do not work when user like and unlike without reload the page, it just get the first click and after that user need to reload the page to it works.
I had a similar issue before and it was something with event delegation.
Use the comment line in your code without "#like_post":
$("#like_post").on("click", function (e) {
});

Text and font-awesome icon wont change on toggle

I am trying to change the text of a button when clicked and back to normal when clicked again. The button is using a font awesome icon so figured I would try using this.html instead of this.text, but for some reason it is not recognising the HTML I am indicating?
If I change the HTML on the else statement then it will change on click which is what makes me think it is an issue with it not recognizing my HTML.
I know it might be something really stupid but cant seem to figure it out.
$(document).ready(function(){
$("#submitbutton").on("click", function(){
if($(this).html()=="View code <i class=\"fas fa-chevron-right fa-xs\"></i>")
{
$(this).html("Close code <i class=\"fas fa-chevron-right fa-xs\"></i>");
} else {
$(this).html("View code <i class=\"fas fa-chevron-right fa-xs\"></i>");
}
})
});
<div class="getcodebuttoncontainer">
<button
type="button"
class="btn-primary"
id="submitbutton"
onclick="retrieveData()"
>View code <i class="fas fa-chevron-right fa-xs"></i></button>
</div>
It seems as if the only change is the text ( "View || Close ") so you can simply put that variable text in spans - one with a display: none styling and then on the click - toggle the visibility of each.
$(document).ready(function(){
$("#submitbutton").on("click", function(){
$(this).find('span').toggle();
})
});
#submitbutton span:nth-of-type(2) {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="getcodebuttoncontainer">
<button
type="button"
class="btn-primary"
id="submitbutton"
>
<span>View</span>
<span>Close</span>
code <i class="fas fa-chevron-right fa-xs"></i>
</button>
</div>

How to emulate an enter key just cliking a button?

I am just wondering about how can I emulate an ENTER key clicking a button. It is designed as this image, as it is an input field, its working with the enterkey and its inserting the text correctly.
But the button designed has to work as if the "enter" key has been pressed.
For example:
Text: "Hi there"+ENTER KEY --> WORKS WELL;
Text: "Hi there"+ Click button as ENTER KEY PRESSED --> I dont know how to implement it.
The code is the below:
<div class="message-input">
<input name="message" id="textEle" placeholder="Escribe aquí...">
<button class="sendMsg">
<span id="sendBtn" class="fa-stack fa-2x visible-xs">
<i class="fa fa-circle fa-stack-2x" style="color:#0f2638"></i>
<i class="fa fa-paper-plane-o fa-stack-1x fa-inverse"></i>
</span>
</button>
</div>
I have already the following javascript code, where is cheking every single input key and when its the ENTER one it makes the insert action:
Template.channel.events({
'keyup [name="message"]' ( event, template ) {
handleMessageInsert( event, template );
}
}
Please let me know if there is any way to do it.
Thanks a lot!
So with native JS:
// buttonEle would be your button, textEle would be your text input
buttonEle.addEventListener('click', function (e) {
var event = document.createEvent('KeyBoardEvent');
event.initEvent('keypress', true, false);
event.key = 'Enter';
event.keyCode = 13;
// now dispatch the event from whichever element your other listener is bound on im gonna assume this is the text input
textEle.dispatchEvent(event);
});
Or with jquery
$(buttonEle).on('click', function (e) {
var event = jQuery.event('keypress', {'keyCode': 13, 'key': 'Enter'});
$(textEle).trigger(event);
});
#prodigitalson's answer in the meteor way:
template.html
<template name = "magic">
...
...
<div class="message-input">
<input name="message" placeholder="Escribe aquí...">
<button class="sendMsg">
<span id="sendBtn" class="fa-stack fa-2x visible-xs">
<i class="fa fa-circle fa-stack-2x" style="color:#0f2638"></i>
<i class="fa fa-paper-plane-o fa-stack-1x fa-inverse"></i>
</span>
</button>
...
...
</template>
template.js
Template.magic.events({
// when you click the button
'click .sendMsg' (event){
event.preventDefault();
// same #prodigitalson's code
var e = jQuery.Event("keypress");
e.which = '13';
$(textEle).trigger(e);
}
});
Edit : Check out this answer for simulating a keypress.

JQuery's .html() sometimes acting weird in Chrome

I have a button:
Now I have a method on that button:
function showPreview(event) {
var button = event.target;
$(button).empty().html('<i class="fa fa-spinner fa-pulse"></i>');
$.post(
...,
function (data) {
...
$(button).empty().html('<i class="fa fa-fw fa-file-pdf-o"></i> Preview');
}
);
}
Sometimes (rarely) when I click the button in Chrome, it ends up looking like this:
But when I check in the page inspector in Chrome, it reveals that there's only 1 icon and 1 "Preview" string in the button.
I've tested this with other browsers, and none share a similar bug.
Browsers I've tested this with:
Internet Explorer 11
Firefox
Opera
Safari
I have concluded this to be a Chrome bug, and this is unacceptable behaviour. As you can see I'm already trying to empty the button before adding new content to no avail. Is there any other workaround for this specific problem?
Here's my JSFiddle: https://jsfiddle.net/spe0asbo/2/
Please take note that this only happens rarely. It might not happen at all to you.
Give the button an ID and replace event.target with the button element itself.
HTML:
<button id='btn01' type="button" onclick="javascript:showPreview(event);">
<i class="fa fa-fw fa-file-o"></i> Preview
</button>
JS:
function showPreview(event) {
var button = $('#btn01');
$(button).attr("disabled", "disabled");
$(button).html('<i class="fa fa-fw fa-spin fa-spinner"><i>');
setTimeout(function() {
$(button).html('<i class="fa fa-fw fa-file-o"></i> Preview');
$(button).removeAttr("disabled");
}, 2000);
}
See the JSFiddle link here : https://jsfiddle.net/4h5pehr9/
It only happened when I double-clicked the button.
Check my changes: https://jsfiddle.net/ag0ztLna/3/
function showPreview(event) {
var button = event.target;
$(button).attr("disabled", "disabled");
$(button).html('<i class="fa fa-fw fa-spin fa-spinner"><i>');
setTimeout(function() {
$(button).html('<i class="fa fa-fw fa-file-o"></i> Preview');
$(button).removeAttr("disabled");
}, 2000);
}

Audio wont play after loading contents with AJAX

First of all im new to jquery i have tried googling my problem , spent hours to fix this and i couldn't find any , so here i am .
In the below code i have fetched some information ( Songs details ) from database and loaded them to div via ajax .. Up to this point everything works just fine .
script using to load content via AJAX
$(document).ready(function() {
$("#results" ).load( "ajax/profile_ajax.php"); //load initial records
//executes code below when user click on pagination links
$("#results").on( "click", ".pagination a", function (e){
e.preventDefault();
$(".loading-div").show(); //show loading element
var page = $(this).attr("data-page"); //get page number from link
$("#results").load("ajax/profile_ajax.php",{"page":page}, function(){ //get content from PHP page
$(".loading-div").hide(); //once done, hide loading element
});
});
});
<div class="loading-div"><img src="../pagination/ajax-loader.gif" ></div>
<div id="results"></div><!-- content will be loaded here -->
Script im using to play audio
$(function () {
var curAudio;
$(".playback").click(function (e) {
e.preventDefault();
var song = $(this).next('audio')[0];
if (curAudio && song != curAudio && !curAudio.paused) {
curAudio.pause();
$(curAudio).prev().html('<i class="fa fa-play"></i> Play');
}
if (song.paused) {
song.play();
curAudio = song;
$(this).html('<i class="fa fa-pause"></i> Stop');
} else {
song.pause();
curAudio = undefined;
$(this).html('<i class="fa fa-play"></i> Play');
}
curPlaying = $(this).parent()[0].id;
});
});
I have above code to played the fetched music . Now the problem is None of the Buttons are functional even though my code worked fine before i use AJAX .
My Fecthed HTML is like this
<div id="4">
Track Name :- <b>Heros</b>
<br />By :- <a target="_blank" href="../members/profile.php?id=1">USER NAME</a>
<br />
<button class="playback btn btn-primary btn-sm hdnbtn"><i class="fa fa-play"></i> Play</button>
<audio src="../members/memberfiles/1/Heros.mp3">
Your browser does not support HTML5 audio.
</audio>
<a class="btn btn-sm btn-success hdnbtn" href="../members/downloader.php?fld=1&name=Heros.mp3" name="dwn"><i class="fa fa-download"></i> Download MP3</a>
<button class="sharer btn btn-sm btn-danger hdnbtn" type="button"><span class="fa fa-share-alt"></span> Share</button>
<a target="_blank" href="#" class="hide btn btn-sm btn-social btn-facebook socialhdn"><i class="fa fa-facebook"></i> Share on Facebook</a>
<a target="_blank" href="#" class="hide btn btn-sm btn-social btn-twitter socialhdn"><i class="fa fa-twitter"></i> Tweet this </a>
<a target="_blank" href="#" class="hide btn btn-sm btn-social btn-google-plus socialhdn"><i class="fa fa-google-plus"></i> Share on goole</a>
<br />
<i class="fa fa-minus"> Show Less</i>
<input type="hidden" value="Heros.mp3" name="file_name">
<input type="hidden" value="bWVtYmVyZmlsZXMvMS9IZXJvcy5tcDM=" name="link">
What i really need is to play the fetched content using the 2nd script (audio) i posted . i have no idea how to fix this . Tried hours of googling and various suggested methods. None of them worked for me . Please Point out what went wrong . i really appreciate it !
use below code to play audio . you also check Event delegation to attach event to dynamically created element. Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$(function () {
var curAudio;
$(document).on('click',".playback",function (e) {
e.preventDefault();
var song = $(this).next('audio')[0];
if (curAudio && song != curAudio && !curAudio.paused) {
curAudio.pause();
$(curAudio).prev().html('<i class="fa fa-play"></i> Play');
}
if (song.paused) {
song.play();
curAudio = song;
$(this).html('<i class="fa fa-pause"></i> Stop');
} else {
song.pause();
curAudio = undefined;
$(this).html('<i class="fa fa-play"></i> Play');
}
curPlaying = $(this).parent()[0].id;
});
});

Categories

Resources