carpics
carpics

Reputation: 2282

Div inside of anchor, stop redirect

I have next html:

<a href="https://google.com" >
    <div id="first"></div>
    <div id="second"></div>
</a>

Currently when I click to div #first it takes me to https://google.com.I don't want it. I want to not have effect anchor on div #first, so when I click on div #first nothing is happen.

And I cannot handle anchor, let say that I can add javascript just for div #first.

EDIT

I forgot to tell that my div contain form with attached event submit:

<script>
 function submitForm(_this){
    //do Ajax call
    return false;
 }
</script>

<a href="https://google.com" >
    <div id="first"></div>
        <form method="post" onsubmit="return submitForm(this)">
           <input id="email" name="Email" type="text">
           <input id="submit" name="submit" value="Register" type="submit">
        <form>
    <div id="second"></div>
</a>

So if I add this:
<script>
   jQuery("#first").on("click", function (e) { e.preventDefault(); });
</script>

Then my form doesn't work.

EDIT So if add e.stopPropagation() on input submit click, like this

<script>
   jQuery("#submit").on("click", function (e) { e.stopPropagation(); });
   jQuery("#first").on("click", function (e) { e.preventDefault(); });
</script>

It will work fine, but e.stopPropagation(); doesn't work on fine in Safari. In Safari when I click on input submit it still leads me to the anchor link.

Upvotes: 2

Views: 1914

Answers (4)

nabello
nabello

Reputation: 836

I think that this might help (your id says firs but sake of spelling I'll put first)

$("#first *").attr("disabled", "disabled").off('click');

Upvotes: 0

deleted user
deleted user

Reputation: 832

Either dont't put the div in the anchor, or use the following:

document.getElementById('firs').addEventListener('click', function(event) {
    event.preventDefault();
});

Upvotes: 0

jrath
jrath

Reputation: 990

use the following

event.preventDefault()

Upvotes: -1

epascarello
epascarello

Reputation: 207557

cancel the click with preventDefault

$("#firs").on("click", function (e) { e.preventDefault(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://example.com" >
    <div id="firs">X</div>
    <div id="second">Y</div>
</a>

Upvotes: 2

Related Questions