Dorvalla Dorvalla - 9 months ago 53
Javascript Question

Replace loaded url with another via jquery

I am not a gold star medal with Javascript, so please bear with me.

We have an addition on the site that is being loaded externally via a a javascript (its called ratecard), however the link that is supplied that the item is being used for isnt correct, so with a little javascript/jquery we are trying to overwrite it.

As the plugin is loaded it adds to a predefined div a location.href. I am trying to overwrite this via following javascript.

This is the div that is being generated

<div class="wdgt_widget" style="border:1px solid #1d8be0 !important; border-radius:8px !important; padding:11px !important; width:300px !important; height:64px !important; cursor:pointer !important; box-sizing: border-box !important;" onclick="location.href=''"></div>

So I am trying to unbind the click action first and add a new one, yet nothing happens. See script below.

jQuery(document).ready(function ($) {
setTimeout(function() {
$('#wdgt_widget').attr('click' 'location.href="");
}, 5000);

I added a 5 second timer on it, since i wanted to make sure the code would be loaded and div already be generated.

Sadly nothing happens. Is there a possibility to simply use replace on the onclick? or did i do something wrong here?

Answer Source

Problem: 1) This $('#wdgt_widget') You are using # in the selector which is used to select by id. But you have a class in your div so use .

Solution: 1) Replcae the above mentioned syntax with this $('.wdgt_widget')

Problem : 2) You have a missing ' on the end of the attr function and also a , between your click and location.

$('#wdgt_widget').attr('click' 'location.href=""); // , and ' missing.

Solution: 2) change .attr('click' 'location.href="") to .attr('click','location.href=""') Note I added a , in between and ' at the end.