I wrote the following function and put it between script tags in the header of my wordpress website.
function turnShopBlue(){
var location = window.location.href;
if(location === "MY URL GOES HERE"){
var menuItem = document.getElementById("menu-item-3352");
menuItem.classList.add("current-menu-item");
//document.querySelector("#menu-item-3352").addClass("current-menu-item");
}
}
turnShopBlue();
But for some reason the function doesn't run.
Each time I go the URL (page) that I choose in "MY URL GOES HERE", the class current-menu-item doesn't get added. What do I miss?
I've already tried with triple === and double ==, without success.
EDIT SOLUTION:
My mistake was that I placed the script in the header, the problem here is that the script then runs before the entire DOM is rendered. So alot of the variables I instantiate don't have the good values.
The problem was solved by loading the script in the header;
Also, I had to put it in a jQuery document ready function to autoload it on pageload.
Always put your Javascript code at the end (footer) of your body tag. This way, all your HTML will be parsed before any Javascript execution, further, your external scripts must be placed there as well to improve page's loading performance.
<html>
<body>
<tag-name id='menu-item-3352'></tag-name>
<script>
function turnShopBlue() {
var location = window.location.href;
if (location === "MY URL GOES HERE") {
var menuItem = document.getElementById("menu-item-3352");
menuItem.classList.add("current-menu-item");
//document.querySelector("#menu-item-3352").addClass("current-menu-item");
}
}
turnShopBlue();
</script>
<script external Javascript resources></script>
<script external Javascript resources></script>
</body>
</html>
Resource
$(document).ready equivalent without jQuery
Related
I request an external script by adding this to my HTML file:
<script>
$(document).on("turbolinks:load", function() {
$.getScript("https://example.com/script");
});
</script>
Say the content of the script is as follows:
doSomething = function() {
// ...
};
My website is a Ruby on Rails app with Turbolinks, which caches the content of the requested script between page visits. My script tag does not know about this, so if I revisit the page it will request the script again. How do I avoid this? My current solution is to check if the scripts content is known:
<script>
$(document).on("turbolinks:load", function() {
if (!window.doSomething) {
$.getScript("https://example.com/script");
}
});
</script>
But this depends on the content inside the script staying the same. So I would rather check if a script from the source https://example.com/script already exists? Or maybe some other approach. Any ideas?
Like epascarello commented, $.getScript appends to head so check that it's not in head before getting it.
if (!$('head script[src^="https://example.com/script"]').length){
$.getScript("https://example.com/script");
}
Use the Attribute Starts With Selector because $.getScript appends a timestamp to avoid getting an already cached version, i.e. it requests a new URL each time.
If you're going to use it more than once:
function getScriptOnce(url){
let selector = 'head script[src^="' + url + '"]';
if (!$(selector).length){
$.getScript(url);
}
}
getScriptOnce("https://example.com/script");
I am using Laravel 5 where I can make a master page (header, footer) and import every page's content in that master page.
I have a dropdown in my header (master page) and in javascript, I have a variable connected to it - var clickable = true;.
//Master Blade
#yield('content')
<script>
var clickable = true;
$('.dropdown).click(function() {
clickable = false;
})';
</script>
In my view (content), I have a function that I also want to change clickable = true;
//View
('.contentElement').click(function() {
clickable = true;
});
However, it doesn't recognise it. Is there a way that I can achieve what I want to?
Most likely you are referencing a variable that is in a different scope. It is hard to tell if that's the case with your minimal code provided but most likely this is why your variable is not being recognized.
You should not be writing JavaScript in different parts of your template, it will make for hard to maintain code. Instead, put all your JavaScript code in its own .js file and include it in your page.
There are many benefits of doing this, but mostly it will help you better structure your code and save pointless debugging time.
I found my answer. I created
<body>
<script>
var clickable = false;
</script>
....
#yield('content')
<script> /* rest of JS */ </script>
</body>
So I'm not that great with Javascript so I'll put that forward right away. That being said, I've looked up as much as I could on this particular problem before asking, but the suggestions haven't solved my issues. I'm ultimately trying to pull all of the links from an iframe window on the same domain as the main page. Then I want to basically search that link array to match it with the current page to trigger a CSS modification to the html code (this part is not coded yet, FYI). So here is the part I have so far: Side note: The confirms are in there to debug the code and try to tell me where it's failing and what my queries are returning, they won't stay obviously when this is finished. I appreciate any advice that may help me fix this!
<script type="text/javascript">
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
I have created a plunker for you its working. I think its the placement of code in your file is causing the problem.
<iframe id="main" src="content_if.html"></iframe>
<script>
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
You should use jQuery to do this in a cross browser way. Include jQuery in page
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
and follow this post
There is a similar post about doing this and I agree with Mohamed-Yousef. If you can use jquery then you should do so!
$("#main").contents().find("a").each(function(element) {
// "each" will iterate through every a tag and inject them as the "element" argument
// visible in the scope of this anonymous function
});
EDIT:
You must include
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
above your code that references the $ variable. There are other ways to use jQuery but this is probably the easiest.
I'm using jquery's .html() function to inject a html file into a partial div of the main page of my application. In the injected partial html page, there is a javascript reference such as script(src='../../javascripts/partialFunctions.js').
The jquery function and the main page are like:
$('.partialDiv').html(htmlResult);
<div>main page</div>
<div class='partialDiv'></div>
<input type='button'>button</input>
When the user click a specific button on the main application page, the jquery function will got called and the html file will got injected to the main page.
The problem is every time a new htm file got injected, the browser will load the script file. So there will be many duplicated javascript functions after the user clicked the button several times.
How can I do this dynamically and avoid the duplication of javascript functions?
Thanks in advance!
You can remove the script tags and references from the htmlResult page.
Then use $.getScript('myscript.js') to import the necessary JavaScript files.
More info on getScript() here
So to load in the script and make sure it only loads in once:
var window.foo = false; //Outside the document.ready
$('.partialDiv').html(htmlResult);
if(window.foo == false){
$.getScript("js/myScript.js", function(data, textStatus, jqxhr){
console.log('Script loaded');
window.foo = true;
});
}
I just did a quick test, it looks like script tags are stripped out anyways when you call .html(). So you should be able to simply do:
var html = "<html><script></script></html>",
cleanedHtml = $(html).html();
myEl.html(cleanedHtml);
I have a page that i dont have access to its an obvius site. I would like to remove a script html tag with a content. For now i have this but is not working. I am using userscripts like coding!
function main(){
var def = $('script[type="text/javascript"]').html();
$('script[type="text/javascript"]').each(function() {
if (def == 'document.write("<scr"+"ipt type=\'text/javascript\' src=\'http://storing.com/javascripts/"+(new Date()).getTime()+"/3e155555e1b26c2d1ced0f645e_1_1.js\'></scr"+"ipt>")')
$('script[type="text/javascript"]').remove();
}
}
UPDATE:
<script type="text/javascript">document.write("<scr"+"ipt type='text/javascript' src='http://somedomain.com/javascripts/"+(new Date()).getTime()+"/3e1a0cd37f25a6e1b26c2d1ced0f645e_1_1.js'></scr"+"ipt>")</script>
This is the whole script what i want to remove... it inserts a div that i am removing right now i just wanted to know if there is any other method. BUt as i see the only is the hosts file thing :)
I don't believe this will work, since a loaded script will already have run.
That said, you probably want something like this:
$('script').each(function() {
if (this.src.substring(0, 31) === 'http://storing.com/javascripts/') {
$(this).remove();
}
});
It's impossible to match the <script> tag based on the output of .html() because that only returns the contents of the element, and not the outer <script> element nor the element's attributes.
When a script is loaded in a page, it is evaluated and executed by the browser immediately after. After the script has been executed, the content of the script tag is irrelevant.
You might be able to achieve what you want by unbinding the events which might have been loaded by the script. Are there any events you want to disable?
If the script is in a certain domain and you want to block all traffic to it, you could add the following entry to your hosts file:
127.0.0.1 storing.com
This will prevent the request to reach it's destination.