I'm working with a Wordpress website, where I'm building a navigation bar. One of the features I'd like to add is where if you're on a certain page, the option in the navigation bar will be bold to represent that is the section of the site you're visiting.
I'm attempting to achieve this using JavaScript, as I have no working knowledge of PHP:
var current_page = document.URL;
var current_option_id="";
if(current_page==="some-url"){
current_option_id="menu-item-34";
}
document.getElementById(current_option_id).getElementsByTagName("A")[0].style.fontWeight="bold";
Basically, my code figures out which page we're on, and will assign the right menu option's id to the current_option variable. Then, the script will attempt to select the
proper menu option, select the link inside that menu option, and change its style.
The problem with this script is that it simply won't work, generating an error where it cannot select the HTML element; document.getElementById(current_option); returns null. However, when I do this in the console, it works fine, and the style is changed properly. Why is this? I know that the current_option variable has the correct value, but the script fails when it tries to select the element to change.
Any suggestions and help are greatly appreciated. If you know how to do this in PHP with something that will integrate nicely with Wordpress, please do share (and explain how your code works!). If I broke any StackOverflow rule, my apologies.
it's hard to say without seeing your code, but is there a chance that your script is being executed before your entire page is loaded (or, more specifically, before the element with id #menu-item-34 has been added to the DOM)?
Try wrapping your script inside a function, and then setting that function as your page's onload handler:
window.onload = function() {
/* code goes here */
};
Related
I'm creating a chrome extension that needs to hook into another script that already exists on my target web page. For simplicity's sake, I'm trying to find the following existing script element on a page and add a console.log() to it.
<script type="text/javascript">
var viewModel = new ScenePlayViewModel('', 'Ace', false);
viewModel
.load('jgWJJ2qsxx')
.then(function () {
sceneDOM = new SceneEditDOM2(viewModel.scene());
sceneDOM.init();
viewModel.isSubmitViaShareUrl(false);
viewModel.isSubmitViaUnityPackage(false);
console.log("HOOK INJECTED"); <--------------------------------------------- line to add
});
</script>
I've tried a number of solutions but none of them have seemed to work. For example, I've tried using a content script to find the script and replace the text, but it appears to run the pre-change script instead of my modified code.
// replaces javascript on website, but doesn't run new version
var scriptLoadScene = $("script:contains('new ScenePlayViewModel')"); // find the script
scriptLoadScene.text("console.log('Hello World')"); // change the text
What should I do? Basically, I'm just trying to change/add scripts to the web page to add more features.
This doesn't exactly answer your question, but hopefully will help you find a solution.
First - hopefully someone with more knowledge than me will confirm or discredit this - from my understanding, the script code is only run once, on page load, unless otherwise triggered by some event. Since Chrome extensions are triggered after the page has loaded, this script will have already been run, and anything inserted after won't run unless triggered.
I suppose you could always call the function again after you've edited it, but I don't have the knowledge or experience to predict what would happen then.
In my experience, I've just added my own '' tags with the code I wanted to run by writing them into the DOM, either into the '' or '' element.
Best of luck.
-brent
I'm experiencing some issues regarding an AJAX script I'm working on.
The page loads perfectly well, and all needed scripts are loaded the same for basic page functionality inside AJAX script, but after hash change, jQuery behaves awkwardly.
Let's take this example.
The custom jQuery script writes an inline CSS propriety for a specific DIV at page loading:
Now, I load the login page for example:
I get back to the main page and inline style disappears as well as the basic loaded functionalities cease to exist after Ajax call:
*
Any experience on this? Does anyone have a clue why this happens? Or even near it... Seems the script unloads on page/hash change, which I don't believe. Or enters in double loop, therefore doubling the classes for HTML. I don't get it.
Already searched a lot and went trough the coding and is fine becasue it works fine alongside with basic HTML. Would appreciate some thoughts on this matter.
Thanks!
I am trying to automatically download a plugin on my wordpress site by implementing phantomJs. For some reason, I cannot seem access the download button (shown below)
This is the HTML code to the image (with domain sensitive information blurred out for security purposes)
So far, I have tried accessing this element by using the following code:
function() {
page.evaluate(function() {
let mainLink = document.querySelector('a[data-slug="better-wp-security"]')
mainLink.click()
})
}
Some things to mention:
This function, as it is part of a larger file, will NOT execute until the page has finished loading.
PhantomJS is executing correctly, there are no problems with permissions
The script before-hand is properly accessing the install plugins page, which I verified by capturing screenshots before trying to click.
I have defined click earlier int he file, it works perfectly.
Any ideas how I can accomplish this? Thanks all!
ADDED INFORMATION:
It seems as if the path from the main div element is as follows:
#the-list .plugin-card plugin-card-better-wp-security .plugin-card-top .action-links .plugin-action-buttons .install-now button
I imagine the solution to this question has something to do with this sequence.
I was able to accomplish this by now going after the data-slug attribute, but rather going after the href element itself. Although I can't generate my own wponce value without the use of the Rest API, I was able to search the document to find an href that contained certain parts of the url. This is the final code below:
document.querySelector('a[href*="action=install-plugin&plugin=better-wp-security"]').click()
That's it! Simple and easy!
I've got an interesting question. I'm running Squarespace # buscadprimero.caminoglobal.org
and need to target the top-right button on the navigation (Ingresar, which means login) to bring up a Javascript form provided to me via embed code. The code itself works fine when included as a code block in the body of a page, but Squarespace only allows navigation buttons at the top to be hyperlinks. There's nowhere for me to add code to the button itself, being that it is a largely consumer platform and works great for straightforward application until you try to change the way it works.
They make an allowance for custom code via a "code injection" menu that adds whatever code you want to the HTML header of the page, so I've been trying to target this div, which does not have an id but who's class is external, with Javascript to replace its contents with an onclick listener to bring up this form. Tracking?
Here's my embed code, which like I said is fine:
<script>// <![CDATA[
!function(e,t){e._cc={}, e._cc.host="https://www.coachingcloud.com/";var n=function(){var n=t.createElement("script"),c=t.getElementsByTagName("script")[0];n.src=e._cc.host+"login.min.js",c.parentNode.insertBefore(n,c)};e.addEventListener?e.addEventListener("load",n,!1):e.attachEvent("onload",n)}(window,document);
// ]]></script>
I've been trying document.getElementsByClassName("external").innerHTML; but when set to a var that returns undefined. New to Javascript but not afraid to learn. I'd like to figure out how to properly target the div, first of all, and then replace its contents (which currently is a link to my 404 page) with a Javascript function that activates on click. Thanks for the guidance!
I've tested the following on your site in Chrome, and have successfully changed the content. The page contained multiple ".collection" elements, so i select only the last one:
JavaScript / jQuery
$("#mainNavigation .collection").last().html("<a href='/newlink'>Test</a>");
Thanks to the great help of #Arg0n, I've now got a working login form that appears in the top-right-most button of my site. Using:
$(function() { $("#mainNavigation .collection").last().html("<span id='cc-login'>Ingresar</span>"); });
as the function to replace the contents of the div in question, I inserted <span id='cc-login'>Ingresar</span> as the call to the provided embed code:
<![CDATA[ !function(e,t){e._cc={}, e._cc.host="https://www.coachingcloud.com/";var n=function(){var n=t.createElement("script"),c=t.getElementsByTagName("script")[0];n.src=e._cc.host+"login.min.js",c.parentNode.insertBefore(n,c)};e.addEventListener?e.addEventListener("load",n,!1):e.attachEvent("onload",n)}(window,document); // ]]>
Turns out that a little jQuery was helpful in accessing the desired div, and setting its html contents was a bit beyond my area of expertise.
Many thanks to the StackOverflow community for helping me learn about targeting page elements with Javascript to procedurally manipulate its contents.
Here's the code in question
I'm trying to create a simple application - each of the three men has a rel="x" attribute attached them. I'm using var regionId = $('img.selected-region').attr('rel'); to make the rel of the currently selected item the value of reginId.
I want to test this out by performing a simple document.write(regionId) command in a div under the pictures of the men. However, it's not working. Have I put the var regionId definition in the right place in the script window?
I'm completely new to javascript so the syntax is confusing to me - and help would be greatly appreciated.
Try this out http://www.jsfiddle.net/T6Jqx/15/
In the HTML, you have document.write in a script tag. At that time, the DOM may not be ready, but more importantly, it only executes once, not every time an image is clicked. I've modified it to print the "rel" attribute each time you click an image.
JSFiddle's script pane is executed after the document finishes loading.