Parameter passing in JavaScript onclick: this.id versus other attributes - javascript

I suspect there is something basic about JavaScript parameter passing that I do not understand.
If I click on this button, I get an 'undefined' message in the alert box.
<button onclick="play_audio(this.src)" src="foo.m4a">▶</button>
If I click on this button, the string value is passed properly:
<button id="foo.m4a" onclick="play_audio(this.id)">▶</button>
Codepen here:
https://codepen.io/anon/pen/JBpMYo

A button does not have a src attribute. However, you can use this.getAttribute('src').
<button src="foo.m4a" onclick="play_audio(this.getAttribute('src'))" >▶</button>
<script>
function play_audio(src){
console.log("Playing "+src);
}
</script>
It is recommended that you usedata-src (you can use any prefix after data-, not necessarily src) and this.dataset.src instead (you can use the data-* attribute to embed custom data) because it will ensure that your code will not clash with HTML Element attributes for future editions of HTML. See the documentation.
<button data-src="foo.m4a" onclick="play_audio(this.dataset.src)" >▶</button>
<script>
function play_audio(src){
console.log("Playing "+src);
}
</script>

Related

error while changing element in DOM using vannilla JS

I have create a program to change an element in a HTML while a button is clicked, but it causes an error
<button id='change'>hi</button>
<p id="pp">text</p>
<script>
var myfunction=function(e){
e.preventDefault();
document.getElementById('pp').innerHTML=<p id="pp">change</p>
}
document.getElementById('change').addEventListener('click',myfunction(e))
</script>
codesand box link
https://codesandbox.io/s/bold-waterfall-90e74
you have 2 problems. one is you're passing the return value of myFunction into .addEventListener with the value of e which is not defined. the other is your not setting the .innerHTML correctly. I'm not sure if you can create HTML elements in JavaScript using HTML syntax, but if you can, you're creating another <p> element with the same id. Also, .innerHTML should be a String and all HTML attributes should have double quotes. try this:
document.getElementById('change').addEventListener('click', function (e) {
e.preventDefault();
document.getElementById('pp').innerHTML = "change";
})
<button id="change">hi</button>
<p id="pp">text</p>
You also probably shouldn't create functions with var functionName = function() {...} because it can cause hoisting problems. var is also deprecated and can cause bugs so I would advise to use const and let.
fix this string:
document.getElementById('change').addEventListener('click', myfunction)
You were missing quotes around the innerHTML value.
When calling addEventListener, your EventListener is the function "myfunction". You don't have to call it.
<button id='change'>hi</button>
<p id="pp">text</p>
<script>
var myfunction=function(e){
e.preventDefault();
document.getElementById('pp').innerHTML='<p id="pp">change</p>'
}
document.getElementById('change').addEventListener('click',myfunction)
</script>

How to pass tag parameter to onclick function?

I hava a js function like this...
function myfunction(data){
console.log(data);
}
and I need to pass parameter from data in a tag. I tried to do:
<a id="aTag1" data="some data" onclick="trees(this);" > click me </a>
I expect to print in console "some data" but instead the console print all the html a tag
Also I tried with console.log(data['data']) and console.log(data.data) but its undefined
How can I receive the data parameter from the a tag?
You pass the reference of the element, so you need to look at the attributes. Ideally you should use a data attribute.
function myfunction(elem){
console.log(elem.dataset.test);
}
<a id="aTag1" data-test="some data" onclick="myfunction(this);" > click me </a>
You need to reference the datset value. You are console logging the entire tag rather than the attributes value. You can also use el.getAttribute() as well.
Important notes: In your example you are passing data into your function. data is a reserved word used in both HTML and in JS, I would recommend passing a different parameter into your function. Also your data- attribute needs a property to go along with the data attribute to make it work as intended. Example: data-info, data being the prefix and info is the propert, together data-info, it is read using dataset.info. MDN: Using attributes and MDN: More on Data Attributes
function trees(data){
console.log(data.dataset.some);
console.log(data.getAttribute('data-some'))
}
<a id="aTag1" data-some="some data" onclick="trees(this);" > click me </a>
Basically when you pass this, you're passing the whole element object. The thing you want can be achieved by the following snipped:
function myfunction(data){
console.log(data.attributes.data);
}

Map separate button to separate CSS file to change background image of my page

I am trying to change the background of my page using angular f/w by calling the different CSS files on click of different button on the same page.
CSS1.css
body {
background-image: url("./Images/mg.jpg");
}
CSS2.css
body {
background-image: url("./Images/mg.jpg");
}
In the html file i am trying to create 2 buttons such that on click of button1, CSS1.css file will be called and on click of button2, CSS2.css file will be called.
I am trying to access a CSS file by creating an ID to the button and mapping script function function to it but i am getting some runtime error
HTML File
<button type="button" id="button1" onclick="myFunction()">background1</button>
<link rel="stylesheet" type="text/CSS" href="CSS1.css" id="theme">
Script file
function myFunction()
{
document.getElementById("button1")= document.getElementById("theme");
}
Can you please lemme know what am I doing wrong here?
Thanks.
stylesheet links load the stylesheet right away. You don't need custom Javascript to apply it.
To achieve the effect you want you can remove the link tags and modify the function like that:
function myFunction() {
document.body.style.background = "url('./Images/mg.jpg')";
}
The getElementById() method returns the element that has the ID attribute with the specified value.
The left side document.getElementById("button1") returns a value , the right side also returns a value. This is not allowed.
You could do something like this this:
HTML
<link rel="stylesheet" href="CSS1.css" id="theme">
<button type="button" (click)="myFunction('CSS1.css')"> background1 </button>
<button type="button" (click)="myFunction('CSS2.css')"> background2 </button>
Tip: Note that I changed your onclick to (click). I notice that one of your tags on your question is angular. If you are using angular, then you should use this attribute instead of onclick.
TypeScript
myFunction(sheet: string) {
document.getElementById('theme').setAttribute('href', sheet);
}

Add text to twitter share API via jquery/javascript

I can't manage to make jQuery add the content of #quote (which is a paragraph with a string generated via foresmatic API).The full code is here: https://codepen.io/raffaele2692/pen/GvrvxM .... Can you help me? :)
<a type="button" class="twitter-share-button"
href="https://twitter.com/intent/tweet"
data-size="small"
data-text="">
Tweet</a>
<script>
var textQuote = document.getElementByID("#quote");
$("a").attr("data-text", textQuote);
</script>
You have some issues in the js code. You do not need to add "#" to the id for getElementByID call , also to get the text of a HTML element you can use text method.
<script>
var textQuote = $("#quote").text();
$("a").attr("data-text", textQuote);
</script>
I think textQuote is a HtmlElement object, not the value you want to assign.
you should get the value in quote first.
btw, jquery has a method called data to assign value to data attributes.

jQuery chained functions and "this": Where is my syntax incorrect in this example?

Here's the situation:
I have 3 buttons
<button type="button" class="job-update-button wp-core-ui button-primary" id="delete-btn">Remove</button>
<button type="button" class="job-update-button wp-core-ui button-primary" id="update-btn">Update</button>
<button type="button" class="job-update-button wp-core-ui button-primary" id="add-btn">Add</button>
and an input
<input type="hidden" name="jobAction" value="" />
whose value is supposed to relate to the id of whichever button has been clicked. It might look silly, but this is my way of consolidating the logic on the page so that a single script on the server can handle a bundle of related AJAX requests.
delete-btn clicked --> jobAction gets value of delete
update-btn clicked --> jobAction gets value of update
add-btn clicked --> jobAction gets value of add
The function I'm using for the click events starts with
jQuery('.job-update-button').click(function(){
// change the value of the memberAction hidden input based on which member-update-button was clicked
jQuery('input[name="jobAction]"').val(jQuery(this).attr('id').substring(0, this.IndexOf('-')));
and I'm trying to figure out why I'm getting
this.IndexOf is not a function.
My thinking is that by the time I call this.IndexOf('-') the this refers to the object invoking substring, which is the string returned by jQuery(this).attr('id').
Is that wrong? If so, can you help me understand why? And is there a more efficient and compact way of going about this whole procedure?
Your Jquery function is messed up all you need is:
$('.job-update-button').click(function(){
// change the value of the memberAction hidden input based on which member-update-button was clicked
var id = $(this).attr('id');
var value = id.replace("-", " ");
$('input[name="jobAction"]').val(value);
})
For starters you dont need to call jQuery the shorthand way is simply $
It looks like you have a " outta place in your code. Change this:
'input[name="jobAction]"'
To:
'input[name="jobAction"]'
Working codepen example
Please note instead of:
jQuery('.job-update-button').click(function(){}
I used:
$('.job-update-button').click(function(){}
You could call jQuery every time but $ is easier.
If its not what you're looking for just let me know and I will edit or delete.
Let's break your code down a bit to make it clearer:
jQuery('.job-update-button').click( function(){
var value = jQuery(this).attr('id').substring(0, this.IndexOf('-'));
jQuery('input[name="jobAction"]').val( value );
});
Inside the click event handler, this refers to the HTML element that triggered it. That is just the way jQuery works internally (you can explicitly set this or 'scope' when calling or applying a function).
That means you are trying to call indexOf (note the correct spelling) on an HTML element, which does not have an indexOf method.
Also, note that most people use the $ shorthand for the jQuery method.
To fix your code, this would probably suffice:
$('.job-update-button').click( function(){
$('input[name="jobAction"]').val( $(this).attr('id').replace(/-btn$/, '') );
});
Here, I'm using the replace method with a Regular Expression in order to strip out the appended '-btn' part of the id.

Categories