-2

This is relevant to this problem (which has been solved): Previous Problem:Solved, just to give context to the question.

What I want to do is to apply the link that I've got from the previous code, into a href in a button element. This is what I've got so far:

<script type="text/javascript">
var newestLink = "";
window.setTimeout(function(){
    var newLink = $('.link:last').attr("href");
    newestLink = newLink;
}, 1500);

window.setTimeout(function(){
alert(newestLink);
document.getElementById('#redButton').onClick = function() {
  document.getElementById('#redButton').href=newestLink;
}
}, 3000);
</script>

The alert code is just to check that I have the correct value. When I use this code, the console return an error Uncaught TypeError: Cannot set property 'onClick' of null (anonymous function)

I can't seem to understand where the code gone wrong. I'm following this advise.

Community
  • 1
  • 1
Hafiz Hanif
  • 361
  • 1
  • 3
  • 20

3 Answers3

3

You mixed up javascript and jQuery syntax. Javascript is document.getElementById('redButton') and jQuery is $('#redButton').

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
1

You should either use jQuery or the basic JavaScript Selector Style. If you mix them up this sort of typos can occur.

jQuery Style:

<script type="text/javascript">
    var newestLink = "";
    window.setTimeout(function(){
        var newLink = $('.link:last').attr("href");
        newestLink = newLink;
    }, 1500);

    window.setTimeout(function(){
        alert(newestLink);
        var node = $('#redButton');
        node.click(function() {
            node.attr('href', newestLink);
        });
    }, 3000);
</script>

A better way to do this then using some nasty timeouts is to use the ready event fired as soon as the DOM is ready:

<script type="text/javascript">
    $(function(){ // execute this code on ready
        var newLink = $('.link:last').attr('href');
        var node = $('#redButton');
        node.click(function() {
            node.attr('href', newestLink);
        });
    });
</script>
Simon
  • 26
  • 1
  • Thank you for your awesome code! I've used it and tweaked it a bit. I'm not using the DOM ready function because the page loads a picture gallery, which takes a bit of a time, and if i'm not mistaken DOM ready doesn't take into account images, right? – Hafiz Hanif Feb 17 '15 at 14:50
  • You can use $(window).load(function(){ ... }); instead of the ready event. Load should be triggered after the images are available. – Simon Feb 18 '15 at 10:32
0

please copy n paste below code work well in both chrome and mozilla without consol error.

<script type="text/javascript">
var newestLink = "";
window.setTimeout(function(){
var newLink = $('.link:last').attr("href");
newestLink = newLink;
}, 1500);

window.setTimeout(function(){
alert(newestLink);
$("#redButton").click(function(e) {
    $(this).prop("href",newestLink);
});
}, 3000);
</script>
Nikhil sHETH
  • 510
  • 4
  • 11