jquery script removal - asp.net

I need to remove the following script from my page(ASP.NET 3.5), leaving all other scripts intact:
<script type="text/javascript">
//<![CDATA[
alert('Save Sucessful.');
</script>
Should be something like $('html').children('script').remove(':contains("alert")) but this exact syntax doesn't work.

Rather than a pop-up alert, why not provide feedback with a page element (in the DOM)?
It would be there still rather than be there again.
Okay, if you cannot change it you could replace the windows.alert function, if it's executed before the code in question (usually in DOM order).
BTW, you can't just test the string (my first thought) since "Successful" should have two 'c's and the owner of that code might fix it.
But you could mute all alerts for the first 10 seconds with:
var _alert = window.alert, _alertStart=new Date().getTime();
window.alert = function() {
var delay = (new Date().getTime()) - _alertStart;
if (delay > 10000)
_alert.apply( window, arguments );
};
Or, if you want to delete every inline script that contains "alert" you could use:
$('script:contains("alert")').remove();
Note that that pattern matches the script tag in which it occurs, so you could change it if it matters:
$('script:contains("al'+'ert")').remove();

$('html').children('script:contains("alert")').remove();

Related

jsdom does not fetch scripts on local file system

This is how i construct it:
var fs = require("fs");
var jsdom = require("jsdom");
var htmlSource = fs.readFileSync("./test.html", "utf8");
var doc = jsdom.jsdom(htmlSource, {
features: {
FetchExternalResources : ['script'],
ProcessExternalResources : ['script'],
MutationEvents : '2.0'
},
parsingMode: "auto",
created: function (error, window) {
console.log(window.b); // always undefined
}
});
jsdom.jQueryify(doc.defaultView, 'https://code.jquery.com/jquery-2.1.3.min.js', function() {
console.log( doc.defaultView.b ); // undefined with local jquery in html
});
the html:
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script src="./js/lib/vendor/jquery.js"></script>
<!-- <script src="http://code.jquery.com/jquery.js"></script> -->
<script type="text/javascript">
var a = $("body"); // script crashes here
var b = "b";
</script>
</body>
</html>
As soon as i replace the jquery path in the html with a http source it works. The local path is perfectly relative to the working dir of the shell / actual node script. To be honest i don't even know why i need jQueryify, but without it the window never has jQuery and even with it, it still needs the http source inside the html document.
You're not telling jsdom where the base of your website lies. It has no idea how to resolve the (relative) path you give it (and tries to resolve from the default about:blank, which just doesn't work). This also the reason why it works with an absolute (http) URL, it doesn't need to know where to resolve from since it's absolute.
You'll need to provide the url option in your initialization to give it the base url (which should look like file:///path/to/your/file).
jQuerify just inserts a script tag with the path you give it - when you get the reference in the html working, you don't need it.
I found out. I'll mark Sebmasters answer as accepted because it solved one of two problems. The other cause was that I didn't properly wait for the load event, thus the code beyond the external scripts wasn't parsed yet.
What i needed to do was after the jsdom() call add a load listener to doc.defaultView.
The reason it worked when using jQuerify was simply because it created enough of a timeout for the embedded script to load.
I had the same issue when full relative path of the jquery library to the jQueryify function. and I solved this problem by providing the full path instead.
const jsdom = require('node-jsdom')
const jqueryPath = __dirname + '/node_modules/jquery/dist/jquery.js'
window = jsdom.jsdom().parentWindow
jsdom.jQueryify(window, jqueryPath, function() {
window.$('body').append('<div class="testing">Hello World, It works')
console.log(window.$('.testing').text())
})

How can I tell if my Google content experiment is running?

I've created a google content experiment without redirects using the docs.
The basic implementation involves a javascript snippet that uses the following code to choose the version of the experiment:
<!-- Load the Content Experiment JavaScript API client for the experiment -->
<script src="//www.google-analytics.com/cx/api.js?experiment=YOUR_EXPERIMENT_ID"></script>
<script>
// Ask Google Analytics which variation to show the user.
var chosenVariation = cxApi.chooseVariation();
</script>
<!-- Load the JQuery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
// Define JavaScript for each page variation of this experiment.
var pageVariations = [
function() {}, // Original: Do nothing. This will render the default HTML.
function() { // Variation 1: Banner Image
document.getElementById('banner').src = 'bay-bridge.jpg';
},
function() { // Variation 2: Sub-heading Text
document.getElementById('heading').innerHTML = 'Look, a Bridge!';
},
function() { // Variation 3: Button Text
document.getElementById('button').innerHTML = 'Learn more';
},
function() { // Variation 4: Button Color
document.getElementById('button').className = 'button button-blue';
}
];
// Wait for the DOM to load, then execute the view for the chosen variation.
$(document).ready(
// Execute the chosen view
pageVariations[chosenVariation]
);
</script>
However, when I visit the page using an incognito window, I only see the first variation of the experiment. When I check chosenVariation in the console, it's always 0. In fact, when I call cxApi.chooseVariation(); in the console, it always returns 0.
Is this because google recognizes my incognito browser windows, or is something broken with cxApi.chooseVariation(); or in my implementation?
I had the same problem, 100% of the sessions were given the original (0) variation. In order to fix the problem, I added the javascript code provided by the experiment. Go to your experiment (edit), click Setting up your experiment code, manually insert the code, copy the code in there.
Now since you (and I) don't want to have a redirect, remove this part at the end of the code <script>utmx('url','A/B');</script>. If your page is templated, you can use a variable and insert your experiment key (not experiment id) where you see var k='########-#'
Now either very few people use the experiments in a client-only fashion or we're totally stupid because it would seem to me that the guide is wrong and there's absolutely no documentation that shows a working client-only setup.

Wordpress - Changing Background-Color of Multiple Divs

I have multiple DIV elements on my page with the class "grid-item-container"
I want to make the background-color of each one different. I will set an array of 5 different colours that can be set.
There is a script available here that seems to do this: http://jsfiddle.net/VXG36/1/
$(document).ready(function() {
var randomColors = ["green","yellow","red","blue","orange","pink","cyan"];
$(".random").each(function(index) {
var len = randomColors.length;
var randomNum = Math.floor(Math.random()*len);
$(this).css("backgroundColor",randomColors[randomNum]);
//Removes color from array so it can't be used again
randomColors.splice(randomNum, 1);
});
});
I cannot however get it to run on my page. Is there something in this script that needs to be amended to make it Wordpress friendly?
Kind regards
Dave
You might wan't to wrap it in something like this:
jQuery(document).ready(function($) {
// Inside of this function, $() will work as an alias for jQuery()
// and other libraries also using $ will not be accessible under this shortcut
});
The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link. Read more about it in Codex here.
Also, change $(.random) to $(.grid-item-container), this targets the class of your div.

Attaching jQuery plugins to Meteor template-generated DOM elements

According to the Meteor documentation, a callback assigned to Template.template_name.rendered will execute after each instance of template_name has finished rendering. I have been trying to use this feature to attach jQuery plugins (such as TagsManager or DotDotDot) to DOM elements generated by the templates. The "natural" way to do this would be something like:
Template.template_name.rendered = function () {
var template = this;
var elem = $('input#tags'+template.data._id);
elem.tagsManager(); // doesn't work
}
However, this does not work -- the expected behaviors do not come out attached to the element. The jQuery selector works properly and, by logging the internals of tagsManager(), I can see that the event handlers do seem to get attached, but after .tagsManager() finishes up, they are somehow unattached.
The "usual" solutions of wrapping the code in a $(document).ready or a short setTimeout suffer from the exact same behavior:
Template.template_name.rendered = function () {
var template = this;
$(document).ready(function () {
window.setTimeout(function () {
var elem = $('input#tags'+template.data._id);
elem.tagsManager();
}, 100); // 0.1 seconds + $(document).ready doesn't work
});
}
I only got it to work by giving an unrealistically high setTimeout time, such as 3 seconds:
Template.song.rendered = function () {
var template = this;
console.log("Template for "+template.data.title+" created");
$(document).ready(function () {
window.setTimeout(function () {
var elem = $('input#tags'+template.data._id);
elem.tagsManager();
}, 3000); // 3 seconds + $(document).ready works
});
}
As a matter of fact, even replacing elem.tagsManager() by a simple elem.on('click',...) suffers from the same behaviors as described above -- which is why the guys at Meteor have given us Template.template_name.events, I guess. However, this kind of breaks all interesting plugins, and forces us to rely on hacky, dangerous code such as the above. Is there a better way?
In the template, wrap the div you want to apply the jQuery with {{#constant}} helper. This will kill all reactivity you may have on elements wrapped up.
If you need reactivity or constant did not help, try this hack. I unbind the event of the element when rendered is called and bind it right after. The problem in this case is that rendered is called like a dozen times and it screw up some way I haven't figured out. Try debugging it to see how many it is called with console.log in the first line of rendered.
Hope it helps!
check that package : https://github.com/Rebolon/meteor-animation/blob/master/meteor-animation-client.js
line 38 to 56
it uses template.rendered with a cursor observer.
It might help you coz it also uses jquery.

Custom Controls and Web Resources (scripts)

I am developing a Server Custom Control (.NET), a "DatePicker" with the jQueryUI Plugin.
So, i have the next script, that is loaded as a webResource:
JavaScript
$(function () {
$("#" + ctrlInput).datepicker({
maxDate: MaxDate,
minDate: MinDate
});
});
As you can see, i have javascript variables, so, for loading the script and the variables, i do the next:
C#
string javascriptVariables = String.Format(
"var MinDate = '{0}'; var MaxDate = '{1}'; var ctrlInput = '{2}';",
MinDate ?? DateTime.MinValue.ToShortDateString(),
MaxDate ?? DateTime.MaxValue.ToShortDateString(),
_textBox.ClientID
);
// Load javascript variables (it will be load every time i add a control)
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "dateValues" + _textBox.ClientID, javascriptVariables, true);
// Load jQueryPlugin (it is loaded only once, and this is the problem)
Page.ClientScript.RegisterClientScriptResource(this.GetType(), "[[resourceName]]");
It works fine. The problem is when i add this control to a page more than once.
And it is because the script variables are loaded fine, but the RegisterClientScriptResource doesn't load the jQuery Plugin again! And i don't know how i can force the load! Because i can't set the resource key to the RegisterClientScriptResource
Does anybody know how to solve this?
Thanks
I don't think you're taking the problem the right way.
Using global variables (in js) especially when they're actually only used locally is a very bad idea. source
Loading jQuery or a jQuery plugin more than once can also be a source of bugs. source
What i would do is to think of another way of passing variables to your javascript, something like data attributes.
You're probably having an html input generated with from server control, add data attributes for your dates :
<input type="text" ... data-mindate="01/01/2013" data-maxdate="12/31/2013" />
Next step is, instead of feeding the global variables to the datepicker function, use the data attributes :
$('#whatever').data('mindate');
or
$('#whatever').attr('data-mindate');
And a fast demo : http://jsfiddle.net/JjemN/

Resources