JQuery toggle() html data - javascript

I have tried searching for a solution to this but can't seem to find a working answer. I may have missed something obvious.
I have a link to show the latest comments on a status. When the link is clicked the link data changes to "Close" (all good) but when close is then clicked to toggle the DIV the link data stays "Close", I want it to return to the original text (i.e 3 Comments).
The HTML:
<a class="comments" id="coms-<?php echo $statmainID; ?>" href="javascript:;"><i class="fa fa-comment"></i> <?php echo $numComs; ?> Comments</a>
<div id="comss<?php echo $statmainID; ?>" style="display:none;">Comments Here</div>
The JQuery:
$(function(){
$('body').on('click', '.comments', function(){
var cID =$(this).attr('id');
var theID = cID.split("-");
var divID = theID[1];
$('#comss'+divID).toggle("slide");
$('.comments'+divID).html('Close');
return false;
});
});
As always, any help from you guru's is always appreciated.
Kind regards.

You can use data attribute to store the original text. Then you can show it again.
HTML
<body>
<a class="comments" id="coms-1" href="javascript:;" data-id="comss1" data-text="4 Comments">
<i class="fa fa-comment"></i> 4 Comments
</a>
<div id="comss1" style="display:none;">Comments Here</div>
<a class="comments" id="coms-2" href="javascript:;" data-id="comss2" data-text="2 Comments">
<i class="fa fa-comment"></i> 2 Comments
</a>
<div id="comss2" style="display:none;">Comments Here</div>
</body>
JS
$(function(){
$('body').on('click', '.comments', function(){
var cID =$(this).attr('id');
var theID = cID.split("-");
var divID = theID[1];
$('#comss'+divID).toggle("slide");
var comments = $('#coms-'+divID);
if($(comments).text() === "Close"){
$(comments).html($(comments).data("text"));
} else {
$(comments).html('Close');
}
return false;
});
});

WORKING FIDDLE
var prevText=$(".comments").text();
$(".comments").click(function(){
if($(this).text().indexOf("Comments")>=0){
$(this).text("Close");
}
else
{
$(this).text(prevText);
}
return false;
});
UPDATE
FIDDLE WITH STATIC NUMBER OF COMMENTS

You can do it like following. Keep the original text in a data attribute and show it when on Close click.
$('body').on('click', '.comments', function() {
var cID = $(this).attr('id');
var theID = cID.split("-");
var divID = theID[1];
$('#comss' + divID).toggle("slide");
if ($(this).html().trim() != 'Close') {
$(this).data('text', $(this).html());
$(this).html('Close');
} else {
$(this).html($(this).data('text'));
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.css" />
<a class="comments" id="coms-1" href="javascript:;"><i class="fa fa-comment"></i> 1 Comments</a>
<div id="comss1" style="display:none;">Comments Here</div>

Related

jQuery: change link text and icon on click

So I am trying to change the the icon of my link for collapse section alongside with the text of the link.
Here is my code:
<a href="#collapse", class="btn", role="button", data-bs-toggle="collapse" id="btn-collapse">
<i class="material-icons" style="vertical-align: middle;">expand_more</i>
<label style="vertical-align: middle;">PRIMARY TEXT</label>
</a>
<!--CONTENT-->
<script>
$(document).ready(function(){
$('#btn-collapse').on('click', function () {
var text=$('#btn-collapse').text();
if(text === "SECONDARY TEXT"){
$(this).text('PRIMARY TEXT');
$(this).find("i").html("expand_more");
} else{
$(this).text('SECONDARY TEXT');
$(this).find("i").html("expand_less");
}
});
});
</script>
I've been trying to find a solution for this for a while now, but nothing seems to work.. Text changes fine, but the icon completely vanishes on click. I don't think it is a major issue, but there is something I don't get with this. Any help here how to adjust?
$(document).ready(function() {
$('#btn-collapse').on('click', function() {
var thisElement = $(this);
var anchorLabelElement = thisElement.find('label');
if (anchorLabelElement.text() === "SECONDARY TEXT") {
anchorLabelElement.text('PRIMARY TEXT');
thisElement.find("i").text('expand_more');
} else {
anchorLabelElement.text('SECONDARY TEXT');
thisElement.find("i").text("expand_less");
}
});
});
<link href="https://cdn.jsdelivr.net/npm/material-design-icons-iconfont#6.7.0/dist/material-design-icons.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#collapse" , class="btn" , role="button" , data-bs-toggle="collapse" id="btn-collapse">
<i class="material-icons" style="vertical-align: middle;">expand_more</i>
<label style="vertical-align: middle;">PRIMARY TEXT</label>
</a>

Tweeting out a quote from Object.textContent

I've build a page where I pull a random quote from an API and all is working in that regard, but I can't seem to pull the textContent and append it to the tweet button.
Here is my code:
HTML
<div id="quote-box">
<div id="quote-copy">
<i class="fa fa-quote-left" id="quotation"> </i>
<span class="text" id="random-quote"></span>
</div>
<div id="quote-author">
- <span class="author"></span>
</div>
<div id="quote-buttons">
<a class="button" id="instagram" title="follow me on IG!" target="_blank" href="https://www.instagram.com/dopeland/"><i class="fa fa-instagram" aria-hidden="true"></i> Instagram</a>
<a class="button" id="tweet-this" title="Tweet This Quote!" href="https://twitter.com/share" target="_blank" data-size="large"><i class="fa fa-twitter" aria-hidden="true"></i> Tweet This!</a>
<a class="button" id="get-quote" title="Generate a new quote!" href="">New Quote</a>
</div>
</div>
Javascript
function getQuote(){
$.ajax({
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
success: function(data) {
var post = data.shift();
$('.author').text(post.title);
$('.text').html(post.content);
},
cache: false
});
};
function changeColor(){
var colors = ['#7A918D', '#93B1A7', '#99C2A2', '#C5EDAC', '#DBFEB8'];
var randNum = Math.floor(Math.random() * (colors.length - 0));
document.body.style.background = colors[randNum];
$('#quotation').css('color', colors[randNum]);
};
$(document).ready(function() {
getQuote();
changeColor();
var randomQuote = $('#random-quote')["0"].textContent;
$('#tweet-this').click(function(){
$(this).attr('href', "https://twitter.com/intent/tweet?text=" + randomQuote);
});
$('#get-quote').on('click', function(e) {
e.preventDefault();
getQuote();
changeColor();
});
});
So my issue is that whenever I click the tweet button, I am only returned with the link "https://twitter.com/intent/tweet?text="
You can also view my CodePen here: https://codepen.io/dopeland/pen/XgwNdB
Move var randomQuote = $('#random-quote')["0"].textContent; inside of your click listener
Like so:
$('#tweet-this').click(function(){
var randomQuote = $('#random-quote')["0"].textContent;
$(this).attr('href', "https://twitter.com/intent/tweet?text=" + randomQuote);
});
randomQuote is assigned once at the beginning (set to a value of ""). Even though you are calling the click listener, the quote's text is never being written to randomQuote and always stays as "".
Forked and fixed codepen: https://codepen.io/eqwert/pen/owraVK

To get value of the link using Jquery

I am trying to get value of linl which is generated from db using while loop.
When I prees on the link it should show alert window with its name.
while($trackResultRow = mysqli_fetch_assoc($trackResult)){?>
<li>
<a href="#" class="rem"
data-userid="<?php echo $trackResultRow['username']?>"
data-track="<?php echo $trackResultRow['track_name']?>">
<span class="glyphicon glyphicon-thumbs-down pull-right"></span>
</a>
<a href="<?php echo $trackResultRow['track_path']?>">
<span><?php echo $trackResultRow['username']?></span> -
<span><?php echo $trackResultRow['track_name']?></span>
</a>
<hr/>
</li>
<hr>
<?php
}
?>
And Jquery code
$(function() {
$(".rem").on("click", function(e) {
e.preventDefault();
var $link = $(this), // save for later
username = $(this).data("userid"),
track = $(this).data("track");
return alert (username);
});
});
But it does not work....Can anybody help me to fix this code?
You code is working for me, however I noticed that your two anchor tags are very close to each other. Are you adding event listener to first anchor tag and clicking on second? See example code below
$(function() {
$(".rem").on("click", function(e) {
e.preventDefault();
var $link = $(this), // save for later
username = $link.data("userid"),
track = $link.data("track");
return alert(username);
});
});
.glyphicon:after {
content: 'Icon'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<ul>
<li>
<a href="#" class="rem" data-userid="USERNAME" data-track="TRACK_NAME">
<span class="glyphicon glyphicon-thumbs-down pull-right "></span>
</a>
<a href="track_path">
<span>username</span> -
<span>track_name</span>
</a>
<hr/>
</li>
<li>
<a href="#" class="rem" data-userid="USERNAME" data-track="TRACK_NAME">
<span class="glyphicon glyphicon-thumbs-down pull-right "></span>
</a> -
<a href="track_path">
<span>username</span> -
<span>track_name</span>
</a>
<hr/>
</li>
</ul>

Add dynamic element onClick and make link disable then removing it with link clickable again

I want to add an dynamic input element onClick with jQuery and make the link disable. On deleting the input element that I just added I want to make the link clickable again.
I did the first part of adding element and making the link disable but the problem is when I add multiple elements and try to delete only one element all other links become clickable. I know, because I have given class to dropdown links. Not sure what to do to get this working right.
Here is my code:
$(document).ready(function() {
$(".list").on('click', function() {
$("#blockFeild").append(
'<div class="row parent">' +
'<div class="col-md-8">' +
'<input class="form-control" type="text">' +
'</div>' +
'<button class="btn btn-info" id="editbtn"><i class="fa fa-pencil" aria-hidden="true"></i></button>' +
'<button class="btn btn-danger" id="removebtn"><i class="fa fa-trash-o" aria-hidden="true"></i></button>' +
'<br><br>' +
'</div>'
).show();
});
});
$(document).on('click', 'a.list ', function() {
$(this).addClass('no-click');
});
$(document).on('click', 'li.block', function() {
$(this).addClass('not-allowed');
});
$(document).on("click", "#removebtn", function() {
$(this).closest('.parent').remove();
$(".block").removeClass("not-allowed");
$(".list").removeClass("no-click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Add Block
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<?php $users_fields=$ this->db->list_fields('users'); for ($i=0; $i
<count($users_fields); $i++){ ?>
<li class="block">
<a class="list" href="#">
<?php echo $users_fields[$i]?>
</a>
</li>
<?php } ?>
</ul>
</div>
Your problem stems from duplicate ids (#removebtn, remember ids must be unique) and also this section of your code:
$(".block").removeClass("not-allowed");
$(".list").removeClass("no-click");
These two lines grab all elements on the page with the classes "not-allowed", and "no-click" respectively and then remove those classes. This is why the removal of one of your rows enables all your dropdown links again.
You need to create a way to associate a generated row with ONLY the link used to generate it, perhaps through the addition of an identifying class on both the row and link. That way when the row is destroyed you can use jQuery to grab that specific link element and re-activate it.
UPDATE
Now that I understand the OP better I updated this Snippet with .index() and .eq() in order to associate the correct .block .list with a matched .removebtn. Also replaced .remove() with .hide(). Works perfect.
Change all ids to classes. ex. from #removebtn to .removebtn. You can only have unique ids. When elements are generated, they have the same id, so that's why they are all affected. I don't quite fully understand OP's objective, but I bet having duplicate ids is the root of the problem.
In order to remove a .parent.row on it's own .removebtn replace the last 4 lines with these lines:
$('.list').on('click', function() {
$(this).addClass('no-click');
});
$('.block').on('click', function() {
$(this).addClass('not-allowed');
});
$(document).on("click", '.removebtn', function(e) {
var tgt = $(this);
idx = tgt.closest('.row').index()
$('.block').eq(idx).removeClass('not-allowed').find('.list').removeClass('no-click');
tgt.closest('.row').hide();
});
SNIPPET
$(document).ready(function() {
$(".list").on('click', function() {
$(".blockfield").append(
'<div class="row parent">' +
'<div class="col-md-8">' +
'<input class="form-control" type="text">' +
'<button class="btn btn-info editbtn"><i class="fa fa-pencil" aria-hidden="true"></i></button>' +
'<button class="btn btn-danger removebtn"><i class="fa fa-trash-o" aria-hidden="true"></i></button>' +
'<br><br>' +
'</div>' +
'</div>'
).show();
});
});
$('.list').on('click', function() {
$(this).addClass('no-click');
});
$('.block').on('click', function() {
$(this).addClass('not-allowed');
});
$(document).on("click", '.removebtn', function(e) {
var tgt = $(this);
idx = tgt.closest('.row').index()
$('.block').eq(idx).removeClass('not-allowed').find('.list').removeClass('no-click');
tgt.closest('.row').hide();
});
.no-click {
pointer-events: none;
}
.not-allowed {
cursor: not-allowed;
}
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css'>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Add Block
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li class="block">
<a class="list" href="#">1</a>
</li>
<li class="block">
<a class="list" href="#">2</a>
</li>
<li class="block">
<a class="list" href="#">3</a>
</li>
</ul>
</div>
<section class='blockfield'>
</section>
I faced this problem previously that my code does not work with
$(document).on.....
So firstly you change the duplication of ids as foxinatardis said and test this:
$(document).delegate('.class_off_button', 'click', function (){
//what you want to do
});

Change the onclick of a hyper link

I want to update the click event of the hyperlink onClick and want to update the html inside the hyperlink in jquery
HTML
<a class=" save" href="javascript:void(0);" onclick="save_unsave('unsave','UID','ID',this);">
<div class="jopt_iconwrap" title="Unsave" alt="Unsave" >
<span class="saved"></span>
</div>
Unsave
</a>
Now onlick of save_unsave function i want to update the html design as below:
<a class=" save" href="javascript:void(0);" onclick="save_unsave('save','UID','ID',this);">
<div class="jopt_iconwrap" title="Save" alt="Save" >
<span class=""></span>
</div>
Save
</a>
I am trying to do this in the function:
jQuery
if(type == 'save')
{
var new_type = "'unsave'";
jQuery(elem_obj).html("");
jQuery(elem_obj).html('<a onclick="save_unsave('+new_type+','+uid+','+id+',this);" class="saved" href="javascript:void(0);"><div class="jopt_iconwrap" title="Unsave" alt="Unsave"><span class="saved"></span></div>Unsave</a>');
}
else if(type == 'unsave')
{
var new_type = "'save'";
jQuery(elem_obj).html("");
jQuery(elem_obj).html('<a onclick="save_unsave('+new_type+','+uid+','+id+',this);" class=" save" href="javascript:void(0);"><div class="jopt_iconwrap" title="Unsave" alt="Unsave"><span class="mico"></span></div>Save</a>');
}
How can we do this in jquery.Please help me in the i have the elmenet object in the function.
simply i will suggest you to use replaceWith() in place of .html() it will work properly for you.
$('a').click(function() {
if ($(this).hasClass('save')) {
$(this).removeClass('save').addClass('unsave');
$(this).text('Unsave')
$(this).attr('id','save')
} else {
$(this).removeClass('unsave').addClass('save');
$(this).text('Save')
$(this).attr('id','unsave')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class=" save">
<div class="jopt_iconwrap" title="Save" alt="Save">
<span class=""></span>
</div>
Save
</a>
Try this way
You can replace the onclick event, like this:
$('.save')[0].onclick = function() {
save_unsave('save', 'UID', 'ID', this);
}

Categories

Resources