jQuery click on modal not working

391
November 23, 2016, at 8:31 PM

I am developing this mini chrome extension in which I insert a button(link) into a page and clicking on it(programatically) will bring the modal up. This works when I click it from the console even with the same jQuery command. But when I do it from the script file itself, it just reloads the current page because the link is obviously the current url of the page since the modal is supposed to be opened on top that page. Clicking with mouse manually works too. But I do not know why clicking the link from the file itself just reload the page without opening up the modal.

chrome.runtime.onMessage.addListener(function(res,sender,sender){ 
	var fileurl = chrome.extension.getURL("modal.js") 
 
	var html = "<a href="#" data-modal="#modal2" class="modal__trigger">Modal </a>....the rest of html here'; 
 
	$('#rightCol').prepend(html); 
	var script = document.createElement('script'); 
	script.type = 'text/javascript'; 
	script.src = fileurl; 
	$("head").append(script); 
	 
	$('.modal__trigger')[0].click(); //this click reload the current page without opening up the modal 
	 
});

Answer 1

The injected script takes some time to be parsed and executed.

  • add a timeout before clicking

    setTimeout(function() { $('.modal__trigger')[0].click() }, 1000);
    
  • or use script.onload event

    script.onload = function() { $('.modal__trigger')[0].click() };
    $("head").append(script);
    
Rent Charter Buses Company
READ ALSO
String replacement of mixed text and HTML (client or server-side)

String replacement of mixed text and HTML (client or server-side)

I want to replace strings of text and html on a webpage. This is for the purpose of highlighting pieces of text.

304
Unable to get a specific page url using jquery

Unable to get a specific page url using jquery

I am trying to set position: absolute to. navbar.

264
Age Bracket Dropdown

Age Bracket Dropdown

I have 2 dropdown, the first dropdown compose of age from 18 to 60. My problem is, what I want for my 2nd dropdown is that, for example if the user selects from the first dropdown is 20, the second dropdown most compose of 21-60.

392
how to add dynamically code before body tag using wordpress hook or filter

how to add dynamically code before body tag using wordpress hook or filter

I am working on developing a WordPress plugin. I want to add some content before body tag and after head tag.

380