Replace onclick function of an object using Javascript - javascript

How do I replace the destination URL on a button when using onclick?
<div id="my_button" onclick="window.location.replace('/destination1')">Button<div>
So it would look like this
<div id="my_button" onclick="window.location.replace('/destination2')">Button<div>
The following Javascript code doesn't work though. Why?
<script>
document.getElementById("my_button").onclick="window.location.replace('/destination2')"
<script>

onclick that you have used in tag - is html event attribute, but onclick in tag, that you also tring to change - is div object property.
Both are like "onclick", but it's not the same.
So, if you want to make thing work, do this:
document.getElementById("my_button").onclick = () => window.location.replace('/destination2');
onclick div property need function(callback) not a string

A simple way to do it would be by adding a listener and preventing the default behavior of the event
document
.getElementById('my_button')
.addEventListener('click', function (event) {
event.preventDefault();
window.location.replace('/destination2');
});
working example

element.onclick requires a function to be assigned and differs from the attribute <node onclick=""> where the content will be wrapped up in a function automatically.
If you want to change the attribute, make use of element.setAttribute("onclick", "...");
element.setAttribute("onclick", "window.location.replace('/destination2');");
Behaves similar to:
element.onclick = function() { window.location.replace('/destination2'); };
Another solution would be using the data-attributes which can be accessed by element.dataset.name.
Example:
<div id="my_button" data-path="/destination2" onclick="window.location.replace(this.dataset.path);">Button</div>
And to change it:
my_button.dataset.path = "/otherPath";

Related

I'm trying to add an OnClick function to an element after page load and then make that OnClick function change the text of a separate element

I'm trying to add an OnClick function to 4 elements element on page load and then make those OnClick functions change the text of a separate element. I tried creating a function called AddClick that specified the elementID and then sets an OnClick attribute and seperate function. (I did this four times for each element I want to have the new function activated on click.
I then asked the AddClick to run on page load.
Then I created the functions that would replace the old text of the seperate element. (These should be set to run when the elements are clicked.
Sorry in advance if this was the wrong approach/If I'm not clear. First time posting on here, any help appreciated.
For the HTML the text I am trying to alter is within a div with an ID, but the h4 does not have a specific ID and I cannot add one.
Here is the JavaScript I tried to implement:
<script type="text/javascript">
function AddClick(){
//Name & Number
document.getElementById("o_5794738").setAttribute('onclick', "NewText()");
//Number
document.getElementById("o_5794733").setAttribute('onclick', "OldText()");
//Name
document.getElementById("o_5794723").setAttribute('onclick', "OldText()");
//None
document.getElementById("o_5794728").setAttribute('onclick', "OldText()");
};
window.onload = AddClick;
function NewText() {
document.getElementById("pt_fc_775338").getElementsByTagName(h4).innerHTML = "<h4>New Text</h4>";
}
function OldText() {
document.getElementById("pt_fc_775338").getElementsByTagName(h4).innerHTML = "<h4>Old Text</h4>";
}
Any help is much appreciated.
You can try this:
document.getElementById("demo").onclick = function() {myFunction()};
I found this example on https://www.w3schools.com/jsref/event_onclick.asp
No need to add click event using load you can directly add the click event using .addEventListener (by the way .setAttribute is not for adding any event)
Simply use .addEventListener like this :
document.getElementById("o_5794738").addEventListener('click', NewText);
Read this for more info about .addEventListener()
Here is the demo snippet below :
document.getElementById("o_5794738").addEventListener('click', NewText);
function NewText() {
document.getElementById("pt_fc_775338").getElementsByTagName("h4")[0].innerHTML = "New Text";
}
<button id="o_5794738">Click Me!</button>
<div id="pt_fc_775338">
<h4></h4>
</div>

Finding Triggering Element of onClick function

I'm working on someone's existing code. In the code there are some inline onClick events attached to some input elements, like this one:
<input type="button" id="inputID" onClick="someFunction()"/>
Problem is that I cannot edit that input's HTML, but I can edit the javascript function declaration of that function.
function someFunction(){
//want to console log the ID of the triggering input element e.g. #inputID
}
Is there a way that I could find the ID of the triggering input within the function, without passing any parameters at the time of calling the function (as I cannot edit the HTML)
Don't use inline event handlers. Use event listeners:
function someFunction(event) {
// Use `this` or `event.currentTarget` to get the current target
console.log(this.id);
}
document.getElementById("inputID").addEventListener('click', someFunction);
<input type="button" id="inputID" value="Click me" />
Since you listed in the tags that you're using jQuery, just leave the body of someFunction empty and attach an event listener to your inputs that call that function.
$('[onclick="someFunction()"]').click(function() {
console.log(this.id);
});
https://jsfiddle.net/k8o1umo4/
You can, however it's not cross browser, in IE it's
window.event.srcElement.id
In FF and Chrome, you have to pass it to the inline function like
someFunction(event)
And then you can access it from target property
event.target.id
You could use the global event object to achieve this:
function someFunction() {
var el = window.event.target;
console.log(el.id);
}
Example fiddle
Be aware that this is may have issues in older browsers. An alternative would be to leave the someFunction() empty (as you say that you cannot remove it in the HTML) and instead assign the event handlers through unobtrusive Javascript, from which you can access the element which raised the event through the this reference.
function someFunction() {
console.log(this.id);
}
var el = document.getElementById("inputID")
//remove inline click event
el.removeAttribute("onclick");
//attach click event
el.addEventListener("click", someFunction);
Within the function that was called from addEventListener 'this' will now reference the element from which the event was fired.
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_value_of_this_within_the_handler
First Way: Send trigger element using this
<button id="btn01" onClick="myFun(this)">B1</button>
<button id="btn02" onClick="myFun(this)">B2</button>
<button id="btn03" onClick="myFun(this)">B3</button>
<script>
function myFun(trigger_element)
{
// Get your element:
var clicked_element = trigger_element
alert(clicked_element.id + "Was clicked!!!");
}
</script>
This way send an object of type: HTMLElement and you get the element itself. you don't need to care if the element has an id or any other property. And it works by itself just fine.
Second Way: Send trigger element id using this.id
<button id="btn01" onClick="myFun(this.id)">B1</button>
<button id="btn02" onClick="myFun(this.id)">B2</button>
<button id="btn03" onClick="myFun(this.id)">B3</button>
<script>
function myFun(clicked_id)
{
// Get your element:
var clicked_element = document.getElementById(clicked_id)
alert(clicked_id + "Was clicked!!!");
}
</script>
This way send an object of type: String and you DO NOT get the element itself. So before use, you need to make sure that your element already has an id.
You mustn't send the element id by yourself such as onClick="myFun(btn02)". it's not CLEAN CODE and it makes your code lose functionality.
in your case it would be:
<input type="button" id="inputID" onClick="someFunction(this.id)"/>
js:
function someFunction(clicked_id){
// Get your element:
var clicked_element = document.getElementById(clicked_id);
// log your element id
console.log(typeof tab);
}

Pass uploaded file as a parameter to javascript method

I am passing the uploaded file as a parameter in the JavaScript method. Then Firebug is throwing error like SyntaxError: illegal character.
<input type="file" id="fileUpload" name="employerLogoUpload" />
<a id="_fileUploadLink" href="#" onClick="javascript:ajaxFileUpload(" +document.getElementById('fileUpload').value+ ");">Upload</a>
Please help me out.
If you want to use inline event attributes change your onclick handler to look like this:
onClick="ajaxFileUpload(document.getElementById('fileUpload').value);"
That will, on click, call the ajaxFileUpload() function and pass it the current value of the fileUpload element.
The way you had it your onclick looked like this:
onClick="javascript:ajaxFileUpload("
...and the +document.getElementById('fileUpload').value+ ");" after that was not part of the onclick - the attribute ends with its closing quotation mark. (Also you don't need the javascript: part inside any inline event handler.)
But since you've tagged the question with jQuery you could lose the inline code and put the following in a script block after the elements and/or in a document ready handler:
$("#_fileUploadLink").click(function(e) {
ajaxFileUpload($("#fileUpload").val());
e.preventDefault();
});
The .preventDefault() is there to stop the browser moving to the top of the document when you click the link.
function ajaxFileUpload(val){
...
}
$(document).ready(function(){
$('a#_fileUploadLink').on('click', function(){
var val = $('#fileUpload').val();
ajaxFileUpload(val);
});
});

Replacing html page text by using JQuery

I have a simple javascript code which replaces the page content....by contents of another file(test2.html)
Code:
$(document).ready(function(){
$("[href='#']").click(function() {
function getcontent(url, id) {
$("#id").load("url");
}
});
});
Now am using
<div id = "content">
<p> REPLACE </p>
</div>
click here
So now on clicking click here REPLACE should be replaced by content of test2.html...but its not happening...
I have included the required jquery.js file in my script..
No, this won't work. getcontent is a function defined in a particular scope -- that of the click handler callback function. It is not accessible in the global scope -- the scope that the onClick method receives.
You should use a genuine click handler, perhaps setting data using data attributes:
$('[href="#"]').click(function() {
$('#' + $(this).data('id')).load($(this).data('url'));
});
Using the following HTML:
click here
You have a weird setup. The function getcontent is not defined in global scope, it cannot be found by the onclick event handler in the HTML. There are other issues as well.
I suggest something like:
click here
and
$(function(){
$("a[href^='#']").click(function(){
$(this.href).load(this.rel);
});
});
$('#' + id).load(url);
In your current method above, you are passing string literals, not the variables themselves.
You seem to be misunderstanding what certain parts of your code are doing. Also, I'd recommend giving your href a real id to make things easier. You don't need to use the jQuery 'click' method and ALSO assign an onclick handler inline in the HTML.
Try this instead:
<div id = "content">
<p> REPLACE </p>
</div>
<a id="clickThis" href="#">click here</a>
$(document).ready(function() {
$('#clickThis').click(function() {
$('#content').load('test2.html');
});
});
Your code with some comments:
$(document).ready(function(){
// this will assign a click handler, you don't need an 'onclick'
// attribute on the anchor tag also
$("[href='#']").click(function() {
// but what does your click handler do?
// It defines a function that is never called.
function getcontent(url, id) {
$("#id").load("url");
}
});
});

adding a mouseover to a link through javascript

Simple quick question....
I have the following link html:
<a href="http://www.site.com/" onmouseover="" />
I have a javascript function which I want to enter some onmouseover information into that link dynamically. So, lets say it then becomes this for example if this javascript function is called:
<a href="http://www.site.com/" onmouseover="alert('howdy')" />
any ideas how to do this?
Add name attribute to and assign onmouseover
<a href="http://www.site.com/" onmouseover="" name="xxx"/>
document.getelementsbyname('xxx').onmouseover = function() { alert('howdy') }
Answer was, using setAttribute() javascript.
I think you want to say: dynamically change your href attribute information then you can do it by jquery
//Write code for prompt box and get value (when mouse-over)
$("a[href='http://www.google.com/']").attr('href', 'YOUR_GET_VALUE')
If you can use jquery, see: http://api.jquery.com/hover/
This is better than changing the attribute directly. Your javascript function can dynamically bind/unbind the mouse hover event and execute your alert call.
Otherwise your javascript function will need to dynamically change the attribute but you'll need to work around browser differences to locate the correct element then locate and modify the onmouseover attribute.
two options:
if it's something small:
<a href="http://www.site.com/" onmouseover="this.href = 'http://stackoverflow.com'" />
if you have something more to do:
<script type="text/javascript">
function doSomething(elem) {
elem.href = 'http://stackoverflow.com';
}
</script>
test
Or as stated before: use jQuery or any other framework to make your life a lot easier
The following works for jQuery every time
first the javascript:
$(document).on('mouseenter','.hovLink', function (e) {
e.preventDefault();
e.stopPropagation();
alert('entering ' + e.target.id);
}).on('mouseleave','.hovLink', function (e) {
alert('exiting ' + e.target.id);
});
and here is the HTML
Link

Categories