Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
113
rated 0 times [  119] [ 6]  / answers: 1 / hits: 18336  / 9 Years ago, fri, february 13, 2015, 12:00:00

I have many buttons inside of webpage like this.



<div class=btn btn-sm btn-success mycustom_btn  onClick=javascript:clickinner();>more</div>
<div class=btn btn-sm btn-success mycustom_btn1 onClick=javascript:clickinner();>more</div>
<div class=btn btn-sm btn-success mycustom_btn2 onClick=javascript:clickinner();>more</div>


What i am trying to do is call function clickinner() on button onclick event. I tried to grab the button element by class name and change the target url.
The javascript code is as follows.



<script>
function clickinner(){
var mybtn=document.getElementsByClassName('btn');
mybtn.onClick=location.href='about-us.html';
};
</script>


I don'twant to grab the element by Id so that i have to assign unique id each time. However whenever i click on any of buttons, the target link is not working.
Please help me.


More From » javascript

 Answers
3

The clicked button can be accessed by using this in the clickinner function, no need to get it by class name:



<div class=btn btn-sm btn-success mycustom_btn  onClick=javascript:clickinner(this);>more</div>
<div class=btn btn-sm btn-success mycustom_btn1 onClick=javascript:clickinner(this);>more</div>
<div class=btn btn-sm btn-success mycustom_btn2 onClick=javascript:clickinner(this);>more</div>


Furthermore, you can just directly redirect to the 'about-us' page, since you're already in the click event. So ...



<script>
function clickinner(target) { // Target refers to the clicked element
location.href='about-us.html';
};
</script>


... is enough.



If you need to go to different pages based on which class the button has, you can do something like:



function clickinner(target) {
if(target.classList.contains('mycustom_btn')) {
location.href = 'another-page.html';
} else {
location.href='about-us.html';
}
};

[#67841] Wednesday, February 11, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;