Shawnik Raghav Shawnik Raghav - 2 months ago 5
CSS Question

How to open a link in a new window in javascript and increase counter only on button click?

I am trying to open a link at a specific counter value. For example if the counter value is multiple of 10 then http://www.google.com link opens up automatically in new tab and that counter increases only on button click. I am doing this in JavaScript.

Any help will be highly appreciated. Thank you so much in advance.

My code is -



$('button.counter').click(function myFunction() {
var count = 1;

while (count <= 60) {
if (count == 10) {
window.open("http://www.facebook.com/shawnikraghav");
}
count = count + 1;
}
});

body {
background-color: #e8e8e8;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>

<head>
<title>Test Code</title>
<link rel="stylesheet" type="text/css" href="style.css">

</head>

<body>
<script src="javascript.js"></script>
<button class="counter" onClick="myFunction()">Click</button>
</body>

</html>




Answer

You should define the counter variable outside the function call by click event. In you code, the counter will be initial to 1 each time you click.

And incase you want to check the counter value is multiple of 10, you should change the condition (count%10) == 0

var count = 1;
$('button.counter').click(function myFunction() 
{
    if((count%10 == 0) && (count < 60)) {
       window.open("http://www.facebook.com/shawnikraghav");
    } else {
       document.getElementById("text").innerHTML = count;
    }
    count = count + 1;
});
Comments