How to fix clicking functionality with javascript? - javascript

I have the javascript/html below. When the user clicks on 'heart' or 'coal' it switches to the opposite. However, it only works for 1 click. If I click on 'heart' once, it turns into 'coal'...but if I click on 'coal' now, it doesn't turn into 'heart' again. Any idea on how to fix this?
<script>
$(document).ready(function(){
$('.like').click(function (e) {
$(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");
console.log('liked');
return false;
})
$('.unlike').click(function (e) {
$(this).parent().html("<a href = '#' class = 'like'><div class = 'coal'></div></a>");
console.log('unliked');
return false;
})
})
</script>
<div>
<a href = "#" class = 'unlike'>
<div class = "heart"></div>
</a>
</div>

Use
$('body').on('click', '.like', function () {
});

The problem you are facing is because you are adding dynamically an element (by destroying and recreating it), and the new element have no event click handler bound to it.
The solution is the use of event delegation, you can use jQuery on.
Another solution is instead of create again and again the clicked element, add a generic class, and in its click change the inner HTML and switch the like/unlike classes.
Code:
<div> <a href="#" class='handler unlike'>
<div class = "heart">aa</div>
</a></div>
JS:
$(document).ready(function () {
$('.handler').click(function (e) {
if ($(this).hasClass('like')) {
$(this).html("<div class = 'heart'>aa</div>");
} else {
$(this).html("<div class = 'coal'>bb</div>");
}
$(this).toggleClass('unlike');
$(this).toggleClass('like');
return false;
})
})
Demo: http://jsfiddle.net/At3D9/

#meavo is correct.
Here is a sample jsfiddle with a code sample similar to what you posted.
http://jsfiddle.net/Q2pDG/
$(document).on("click", '.like', function (e) {
$(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");
return false;
});
$(document).on("click", '.unlike', function (e) {
$(this).parent().html("<a href = '#' class = 'like'><div class = 'coal'></div></a>");
return false;
});

Related

Toggle active class on link

Given a script that toggles between two classes, I'm also adding an active state to the currently selected link to set an underline to show active state. However, when clicking the link continuously, it keeps adding the active class, rather than toggling the class on and off. How can I get the active state to show when the link is clicked, and switch off and apply to the other link when the other link is clicked?
JS
const Terms = {
bindEvents () {
this.enTrigger.addEventListener('click', (e) => {
this.langToggle(this.englishContent)
this.enTrigger.classList.add('active')
this.frTrigger.classList.remove('active')
})
this.frTrigger.addEventListener('click', (e) => {
this.langToggle(this.frenchContent)
this.frTrigger.classList.add('active')
this.enTrigger.classList.remove('active')
})
},
init () {
this.englishContent = document.getElementById('english-terms')
this.frenchContent = document.getElementById('french-terms')
this.enTrigger = document.getElementById('en')
this.frTrigger = document.getElementById('fr')
this.bindEvents()
},
langToggle (id) {
this.englishContent.style.display = 'none'
this.frenchContent.style.display = 'none'
id.style.display = 'block'
}
}
document.addEventListener('DOMContentLoaded', () => {
Terms.init()
})
HTML
<div class="terms-nav">
<a id="en">English</a><a id="fr">French</a>
</div>
You could try using something like this to toggle between the two classes. So when you click on one element, it adds the class to itself but removes it from the other one.
JS Fiddle
var english = document.getElementById('en');
var french = document.getElementById('fr');
english.addEventListener('click', function(){
this.classList.add('active');
french.classList.remove('active');
});
french.addEventListener('click', function(){
this.classList.add('active');
english.classList.remove('active');
});

Get text in containing DIV of clicked link

I have the following JS:
$(document).on("click", '.like', function (e) {
$(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");
return false;
});
$(document).on("click", '.unlike', function (e) {
$(this).parent().html("<a href = '#' class = 'like'><div class = 'coal'></div></a>");
return false;
});
I also have the below html:
<div>
45
<a href = "#" class = 'unlike'>
<div class = "heart"></div>
</a>
</div>
I am trying to get the integer 45 returned to the console using JS but am unable to do so. The 45 is in the div. I am trying to get it returned on click using parent/child or next in relation to the existing html.Any advice on how to do this?
I tried doing
id = $(this).parent().text;
console.log(id);
But it doesn't work.
if you're using chrome dev tools or firebug:
console.log(value);
In internet explorer you will need to start the Dev Tools and refresh the page or console.log won't work.
to return a value in the <div> without an id tag on the div:
$(document).on("click", '.like', function (e) {
$(e.target).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");
console.log($(e.target).text());
return false;
});
text is a method, not a property, you have to call it as a function.
var value = $(this).parent().text();
console.log(value);
Try this
var value = $(this).parent().text();
alert($(this).parent().text()); //Alert 45
console.log(value);//print 45 in Console
Use
console.log( $(this).parent().text().trim());
What about this approach with single event handler using toggleClass method:
$(document).on("click", '.like, .unlike', function (e) {
$(this).toggleClass('like unlike');
alert(this.previousSibling.nodeValue);
return false;
});
And we can use plain old javascript to get previous text node value as this.previousSibling.nodeValue.
Demo http://jsfiddle.net/Q69Bb/

jquery click event on element not having a class

How would I make sure that this href element is will fire "click" event unless it does NOT have "disablelink" class.
DO NOT PROCESS:
<a class="iconGear download disablelink" href="#">Download</a>
PROCESS:
<a class="iconGear download" href="#">Download</a>
tried this without success:
$("a.download").not(".disablelink").click(function (e) {
alert('in');
e.preventDefault();
});
This should work:
$("a.download:not('.disablelink')").click(function (e) {
alert('in');
e.preventDefault();
});
If the disablelink class is being added dynamically:
$(document).on('click', "a.download:not('.disablelink')", function (e) {
alert('in');
e.preventDefault();
});
Check this demo: http://jsfiddle.net/d3rXr/1/
$('a.download').click(function(e){
e.preventDefault();
if($(this).hasClass('disablelink')){
return;
}else{
//other stuff;
}
});
Why don't you check when the anchor is clicked, and if it has the class it returns and does nothing, which would be more readable code I guess.
You could go like this:
$("a.download").click(function(e) {
if($(this).hasClass("disablelink")) {
return false;
}
// Normal code
alert('in');
e.preventDefault();
});
Firstly, this probably doesn't work because some links had disablelink added to them dynamically, and after they already had the click handler bound to them.
Secondly, you should just check for that class inside the click handler, like so:
$("a.download").click(function (e) {
if($(this).hasClass('disablelink')){
e.preventDefault();
// link is disabled
}else{
alert('in');
// link is active
}
});

Override javascript click event one time

I would like to replace the default action of an click event for all anchors in a webpage.
When I use this piece of code:
<html> <head> <script>
var list=document.getElementsByTagName("a");
var isChecked = false;
function load () {
for (i=0; i<list.length; i++)
{
var old = (list[i].onclick) ? list[i].onclick : function () {};
list[i].onclick = function () {
if( !isChecked)
{
test();
old();
}
else
old();
};
}
}
function test() {
alert("new action");
isChecked = true;
}
</script> </head>
<body onload="load();">
<a id="nr_1" onClick="alert('test');"> Anchor 1 </A>
<a id="nr_2" onClick="alert('test2');"> Anchor 2 </A>
</body> </html>
When I click an anchor I get the alert out of the test function and then the default function of the second anchor (even when I click the first anchor). When I then again click one of the two anchors I always get the Alert from the second anchor.
How do I put the original onclick functions back for each anchor element? When someone has an solution in jquery I would be glad as well.
EDIT
I was succesfull using this code:
function load()
{
$('a').attr('disabled', 'disabled');
$('a').click(function(e){
if($(this).attr('disabled'))
{
alert("new");
e.preventDefault();
$('a').removeAttr("disabled");
this.click();
}
});
}
On loading of the page this function is called giving all anchor elements a "disabled" attribute. After clicking the element the e.preventDefault() function disables the inline onclick function. Then I remove the "disabled" attribute and call the click function of the element again. because now the element doesn't have a "disabled" attribute only the default function is performed. I'm still open for "more elegant" solutions to this problem, but for now I'm a happy camper!
If you use jQuery you can combine a one-time handler with a persistent handler:
Documentation for .one() and .on()
Working Example: http://jsfiddle.net/Q8gmN/
Sample HTML:
<input type="button" id="click" value="click" />
​
Sample JavaScript:
button.one('click', function () {
console.log('one time function fired');
});
button.on('click', function () {
console.log('persistent function fired');
});
​

select the Div without specific content

Q:
I have the following case :
Div contains a link , i wanna to just select the div without the link,i mean ,when clicking on the div i wanna specific action differs from clicking the link.through some JQuery.
the structure i work on is:(by firebug)
<div class ="rsAptContent">
sql
<a class = "rsAptDelete" href = "#" style ="visibility: hidden;">Delete</a>
</div>
the JQuery code:
<script type="text/javascript">
$(document).ready(function() {
$(".rsAptContent").click(function(e) {
ShowDialog(true);
e.preventDefault();
});
});
function ShowDialog(modal) {
$("#overlay").show();
$("#dialog").fadeIn(300);
if (modal) {
$("#overlay").unbind("click");
}
else {
$("#overlay").click(function(e) {
HideDialog();
});
}
}
function HideDialog() {
$("#overlay").hide();
$("#dialog").fadeOut(300);
}
</script>`
when i click on the link ,i don't want to execute the Jquery code , how to select the div without the link in.
thanks in advance
Are you looking for something like the stopPropagation() code?
$(".rsAptContent").click(function(e) {
e.stopPropagation();
ShowDialog(true);
return false;
});
});
That should stop the link from executing.
http://api.jquery.com/event.stopPropagation/
Edit: Distinguish between clicking the link and clicking on any part of the content except the link
$(".rsAptContent").click(function(e) {
var $target = $(e.target);
if($target.is(a){
// It's the link.
}else{
// else it's not
}
});
});
Check for the clicked target element than perform action
to get info about which element is click use below script
function whichElement(event){
var tname
tname=event.srcElement.tagName
alert("You clicked on a " + tname + " element.")
}
Try this:
$(".rsAptContent").click(function(e) {
if($(e.target).hasClass('rsAptDelete')) return false;
ShowDialog(true);
e.preventDefault();
});
});
If the target is the link the event is cancelled;
If you already have a click handler on the delete link, then just stop the event propagation there by using stopPropagation().
$(".rsAptDelete").click(function(e) {
e.stopPropagation();
});

Categories

Resources