Changing calling javascript function variable with jquery? - javascript

There is a html page like this:
<div id="list"><a onclick = "javascript:addplaylist('shv231a','1');" href="javascript:void(0);">+</a></div>
<div id="list"><a onclick = "javascript:addplaylist('jhr2a13','1');" href="javascript:void(0);">+</a></div>
<div id="list"><a onclick = "javascript:addplaylist('thy2b1k','1');" href="javascript:void(0);">+</a></div>
There are javascript functions
addplaylist('shv231a','1');
addplaylist('jhr2a13','1');
addplaylist('thy2b1k','1');
I want to change value '1' with '2' in javascript function (addplaylist) when user click this
<a id="make2" onclick="" href="javascript:void(0);">Change the value 2</a>
How can I do that with jquery?

The way to do this with jQuery is to move all of the Javascript code into a separate file or script block within the HTML. Any way which abstracts the display (HTML + CSS) from the behavior (Javascript)
This will require a bit of reworking of the HTML. In particular removing the duplicate id fields in favor of having id's be unique. Additionally removing the javascript references from the onclick handler.
<div id="list1"><a>+</a></div>
<div id="list2"><a>+</a></div>
<div id="list3"><a>+</a></div>
Then with jQuery you can specify the behavior of these links directly from the JavaScript. This is true for both the play list links and the one which modifies them to pass '2',
$(document).ready(function () {
var secondArg = '1';
$('#list1 a').click(function (e) {
addplaylist('shv231a1', secondArg);
e.preventDefault(); // Don't follow link
});
$('#list2 a').click(function (e) {
addplaylist('jhr2a13', secondArg);
e.preventDefault(); // Don't follow link
});
$('#list3 a').click(function (e) {
addplaylist('thy2b1k', secondArg);
e.preventDefault(); // Don't follow link
});
$('#make2').click(function (e) {
secondArg = '2';
e.preventDefault();
});
});

This is a possible solution:
<a id="make2" onclick="javascript:changeToTwo();" href="javascript:void(0);">Change the value 2</a>
Javascript
function changeToTwo() {
$('div#list a').each(function() {
$(this).attr('onclick', $(this).attr('onclick').replace("'1'","'2'"));
});
}
If I remember right ie will only select 1 element with the same id so you may want to consider moving it to a class selector

1) Ids should be unique on a page
2) use a class to select
3) keep your functional code out of the markup
HTML:
<div id="1" class="list"><a>+</a></div>
<div id="2" class="list"><a>+</a></div>
<div id="3" class="list"><a>+</a></div>
javascript:
$('.list').each(function ( index, element) {
addplaylist(element.id);
});

Related

How to fire on onclick event on clicking on an anchor text

I would like to fire an onclick event using Javascript whenever an user clicks on "Remoe Item". Given below is the actual code available. The problem is I do not see any id, class to identify the click on this anchor text. Any idea how to do that?
Remove Item
Thanks in advance.
Roy
You can attach the Click Event using this selector [href="#"] and set an attribute data-value.
Run this code snippet:
var removeCartItem = function(value) {
console.log(`You're about to remove this item: ${value}`);
};
var anchors = document.querySelectorAll('[href="#"]');
for (a of anchors) {
a.addEventListener('click', function(e) {
removeCartItem(e.target.getAttribute('data-value'));
});
}
<a href="#" data-value='ci6223000698'>Remove Item</a>
<a href="#" data-value='ci6223000677'>Remove Item</a>
See? the value was printed from your function removeCartItem.
Bonus with jQuery
Using the .data() looks fancier.
Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.
Run this code snippet:
var removeCartItem = function(value) {
console.log(`You're about to remove this item: ${value}`);
};
$('[href="#"]').click(function() {
removeCartItem($(this).data('value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" data-value='ci6223000698'>Remove Item</a>
<a href="#" data-value='ci6223000677'>Remove Item</a>
you need to add an EventHandler:
Remove Item
while you'd need to have a function like this:
function myFunction(myVar) { //... }
or if you prefer adding the handler js side:
document.getElementById('remove').addEventListener("click", function() {
// your stuff
})
or with jQuery:
$('#remove').click(function() { //.... })
example in fiddle:
https://jsfiddle.net/txy5tyg2/1/
further reading:
addEventListener vs onclick
https://www.w3schools.com/js/js_htmldom_eventlistener.asp
You can retrieve all tag and add an event listener.
you can find the examples here,
How to add click event to an element?

How to decide which element is being clicked in jQuery?

I have more similar elements in HTML which are being added continously with PHP. my question is the following:
With jQuery, I would like to add a click event to each of these <div> elements. When any of them is being clicked it should display it's content. The problem is that I guess I need to use classes to specify which elements can be clickable. But in this case the application will not be able to decide which specific element is being clicked, right?
HTML:
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
jQuery try:
$("test").on("click", function()
{
var data = ???
alert(data);
});
UPDATE - QUESTION 2:
What happens if I'm placing <a> tags between those divs, and I want to get their href value when the DIV is being clicked?
I always get an error when I try that with this.
this refers to the element triggering the event. Note that it is a regular js element, so you'll need to convert it to a jQuery object before you can use jQuery functions: $(this)
$(".test").on("click", function()
{
var data = $(this).text();
alert(data);
});
Like this:
$(".test").on("click", function(event)
{
var data = $(event.target);
alert(data.text());
});
this variable contains the reference of current item
$(document).ready(function() {
$(".test").click(function(event) {
var data = $(this).text();
alert(data);
});
})
;
The class selector in jquery is $(".ClassName") and to access the value, use $(this) as such:
$(".test").on("click", function(){
var data = $(this).text();
alert(data);
});
You can use this inside the function which mean clicked div
DEMO
$(".test").on("click", function () {
alert($(this).html());
});

Remove only one div with query

Here is the JsFiddle
I have a button that will add a new header, textbox, and a link when it's click.
But when I click on the remove link. It's removes every new item that was added.
Html:
<div id='main'>
Top of Boby
<div id='main_1'>
<div>
<h3> Item</h3>
<input type="text" />
</div>
</div>
</div>
JS:
$(function() {
$('.AddItem').click(function() {
$('div#main_1').append("<div><h3>Item</h3><input type='text' class='remove_skill'/><a href=''>Remove</a</div>");
});
})
$(function() {
$('.remove_skill').click(function() {
$(this).remove();
});
})
2 issues..
You have never defined the class for the anchor. Add the class to the anchor
You need to remove the enclosing div and not the anchor. Use .closest
Also you need to delegate the event as the elements are being added dynamically
$('#main').on('click', '.remove_skill', function (e) {
e.preventDefault();
$(this).closest('div').remove();
});
Check Fiddle
The problem with the code you've posted is that no links exist at the moment you call $('.remove_skill').click, so you can't add event listeners to them.
I recommend a step-by-step approach. Create, add behaviour, append to the document.
$('.AddItem').click(function () {
var new_element = $('<div class="item"><h3>Item</h3><input type="text"/><a class="remove" href="#">Remove</a></div>');
new_element.find(".remove").click(remove_item);
$('div#main_1').append(new_element);
});
function remove_item() {
$(this).closest(".item").remove();
return false;
}
I recommend <a href="#"> for javascript-handled links.
Alternative solution using a closure:
$('.AddItem').click(function () {
var new_element = $("<div class="item"><h3>Item</h3><input type='text'/><a class="remove" href="#">Remove</a</div>");
new_element.find(".remove").click(function() {
new_element.remove();
});
$('div#main_1').append(new_element);
});
Your problem is that your "Remove" is in an 'a' tag. This causes the page to reload, and removing all of your previous changes.

adding specific class to element on click jquery

I'm having trouble with a simple nav bar that uses jQuery to add and remove a specific class when a certain page is active. I want a class to append to my aLink class depending on which ID is click. If I click on #aboutLink I want .linkActive to be added, but if I click on #sasLink I want .link2Active to be added. The tutorials I've looked at all have a single class being added, but since both my classes are different I need a specific one to be added depending on which ID is click.
HTML:
<div id="mainNav">
<ul id="nav">
<a id="mainLogo" href="/"><li></li></a>
<a id="aboutLink" class="aLink" href="/"><li></li></a>
<a id="sasLink" class="aLink" href="/savings-and-support"><li></li></a>
<a id="external" href="/"><li></li></a>
</ul>
</div><!--/#mainNav-->
I know my jQuery doesn't make sense, but it's all I could come up with. Logically I get it, but I'm lost on the syntax.
jQuery:
$(function () {
$(".aLink").click(function () {
if ($(this) == $("#aboutLink")
$(this).addClass('activeLink');
else $(this).addClass('active2Link');
});
});
Thanks for any input or direction.
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(){
e.preventDefault();
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
You could, instead, use toggleClass() to allow for those classes to be removed by a second click:
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(e){
e.preventDefault();
$(this).toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
Edited in response to question, from the OP, in comments, below:
How would I remove the class so that both links don't appear to be active at the same time?
There's a few ways, but because you're adding different class-names to denote the 'active' state, they're a little inefficient. The first approach is to use a brute-force method, effectively looking for all a elements that have a class attribute and setting that attribute to the empty string, and then adding the linkActive/link2Active class-name to the clicked-on a element:
$('#nav a').click(function(e){
e.preventDefault();
var self = $(this);
self.closest('ul').find('a[class]').attr('class', '');
self.toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
The alternative is to remove the specific classes from the elements who have their id listed in the idToClass object. This is, however, somewhat expensive in that it needs to iterate over the object, retrieving the id, finding the element with that id and then removing a class-name:
$('#nav a').click(function(e){
e.preventDefault();
for (var id in idToClass) {
if (idToClass.hasOwnProperty(id)){
$('#' + id).removeClass(idToClass[id]);
}
}
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
If, of course, you use a common class-name then it all becomes much easier:
$('#nav a').click(function (e) {
e.preventDefault();
var self = $(this);
self.closest('ul')
.find('.commonActiveClassName')
.removeClass('commonActiveClassName');
self.addClass('commonActiveClassName');
});
JS Fiddle demo.
References:
addClass().
closest().
event.preventDefault().
find().
removeClass().
toggleClass().
Since you already have ID tags to easily reference... I think you want something more like this?
$(function () {
$("#aboutLink").click(function () {
$(this).addClass('activeLink');
});
$("#sasLink").click(function () {
$(this).addClass('active2Link');
});
});
Try using this instead:
$(function () {
$(".aLink").click(function () {
var currentId = this.id;
if ( currentId == "aboutLink"){
$(this).addClass('activeLink');
else if( currentId == "sasLink") {
$(this).addClass('active2Link');
}
});
});

Javascript/jQuery close notification fade out

Hello I have made a basic sticky notification that shows on my website, I am trying to make it so you can manually close it by clicking a button but it won't seem to work? Here is my code:
<script>
$(function() {
$("#closeBtn").click(function () {
$(".notification").fadeOut(500);
return false;
});
});
</script>
<div class="notification" id="success">
Message sent
<a href="#" id="closeBtn">
<div class="close">
<div class="closeTxt">X</div>
</div>
</a>
</div>
try using .on() for the elements created dynamically
$(document).on('click','#closeBtn',function() {
$(".notification").fadeOut(500);
return false;
});
Because the element is added to the DOM after page load, you need to use .on() instead of .click():
$(document).on('click', '#closeBtn', function (e) {
e.preventDefault();
$('.notification').fadeOut(500);
});
When the element is added Dynamically you have two choices.
function myFadeOut() {
$(".notification").fadeOut(500);
return false;
}
Using the on:
$(document).on('click', '#closeBtn', myFadeOut);
Or more clean, adding the click directly on the node when you generate it:
var $myNode = $('<div class="someNode"></div>');
$myNode.click( myFadeOut);
$(".foobar").append($myNode);

Categories

Resources