Removing a DOM element using CasperJS - javascript

Okay basically I have a post:
<div class=post>
<div class=content></div>
<div class=content-meta></div>
</div>
thats the prototype of it to help explain
so what I want to do is use some JS to basically delete or hide the div 'content-meta'
Using JQuery I have:
$('.content-meta').remove();
however when I am using CasperJS I am a little puzzled as how I should implement this code.
I am looking to manipulate a post prior to screen capturing it (the screencapture part works fine)
Heres the code (URL's OMITTED) I have been testing with, It picks up the class just fine, but I have no idea where/how to execute the Jquery to remove the detected element prior to screen capture:
casper.start('http://pageurl.com/XYZ', function() {
if (this.exists('.content-meta')) {
this.echo('found .content-meta', 'INFO');
} else {
this.echo('.content-meta not found', 'ERROR');
}
this.captureSelector('resultingcapture.png', '.post');
});
casper.run();
TL;DR How do you execute JS/Jquery from within a CasperJS function?

For execute javascript code from CasperJS, You have to use evaluate() method
The evaluate() method as a gate between the CasperJS environment and the one of the page you have opened; everytime you pass a closure to evaluate(), you're entering the page and execute code as if you were using the browser console.
Your code should be something like this:
var casper = require('casper').create();
casper.start('http://pageurl.com/XYZ', function() {
if (this.exists('.content-meta')) {
this.echo('found .content-meta', 'INFO');
//evaluates an expression in the current page DOM context.
this.evaluate(function(){
//delete div 'content-meta'
$('.content-meta').remove();
});
this.then(function(){
this.captureSelector('resultingcapture.png', '.post');
});
} else {
this.echo('.content-meta not found', 'ERROR');
}
});
casper.run();
Note: This code is going to run only if the webcontext includes jQuery, otherwise you have to remove the div using just javascript.

Related

Meteor won't run jQuery code

I'm trying to run a block of jQuery code that shows and hides a form, but can't find a way to get Meteor to run the code on the client side. Here's the code I'm attempting to use at the moment:
if (Meteor.isClient) {
Template.post.onRendered(function(){
$(document).ready(function(){
$('.replybtn').click(function(){
if( $(this).parent().next().css('display') === 'none' ){
$(this).parent().next().css('display', 'block');
} else {
$(this).parent().next().css('display', 'none');
}
});
});
});
}
I've also tried putting the code in a script tag, which did not work. Strangely, the jQuery portion of the code alone works fine when pasted into the browser console - meaning the bug is likely in how I'm running the code in Meteor, not the jQuery itself. Also, I've confirmed that the template name is correct and can't think of any other issues that could be causing this. Any ideas on why the jQuery code may not be running?
This is probably not the best solution, but it appears that this issue can be fixed by defining a function that creates the event listener and then setting a 2 second timeout to run the function with setTimeout().
You're trying to apply a traditional jQuery pattern when Meteor provides a simple facility to attach event handlers to templates. Here would be the meteoric way:
if (Meteor.isClient) {
Template.post.events({
'.replybtn click'(e){
const selector = e.target.parentElement.nextSibling;
selector.css('display', selector.css('display') === 'none'? 'block' : 'none');
}
});
});

Javascript: change CSS element if jquery GET failed

I have a Javascript in my header that calls an external server to retrieve some information, like this:
$.getJSON("https://domain.tld/json/", function (something) {
var results = //stuff that formats the result, not relevant here;
window.$info = results;
}).fail(function(){
// here's where I need the code to make the warning appear
});
Then in the body I have a warning that should pop up in case the GET request failed:
<div id="warning">Warning text</div>
Problem: the javascript is in the header and I can't change the "warning" div because it has not been created yet.
If I use document.getElementById("warning").style.display='block'; I get an error message saying it is null.
So how do I use the .fail() part of the jquery GET function to make the warning div appear (that is created later) in case the GET function has failed? Or is that not possible? And some 'solution' I tried (don't remember what exactly) even delayed the loading of the whole page. I'd like to avoid that as well.
Thank you for helping me out.
You should hide your html element initialy
<div id="warning" style="display:none;">Warning text</div>
And you can call show() method to display hidden element when get request failed
$("#warning").show();
Your javascript is trying to execute and look for things before the DOM has loaded. You can solve this problem by making sure your javascript only fires when the DOM is ready. In jQuery you do that like this:
$(document).ready(function(){
//your code here
});
The native javascript version of this is much more complicated so I won't post that here. However you could also wait for the entire page to load before executing the code like so:
window.onload = function(){
//your code here
}

Handling jquery event with casperjs

I have a web page where after the dom is loaded javascript continues to run on the page and adds elements onto the page. After all the javascript is run I fire a jquery event page.loaded so that components on the page that are interested in doing something after all my javascripts are run can do so.
I am trying to automate the testing of this webpage using casperjs/phantomjs and I would like to examine elements on the page only after the jQuery page loaded event is fired. How should I go about doing this?
Look at the waitFor family functions in order to wait for something to happen in the page environment. You can either wait for some element or text to be available in the DOM, or directly add a specific jQuery listener in order to process further steps:
casper.start('test.html', function() {
this.evaluate(function() {
$(document).on('site:loaded', function() {
window.siteLoaded = true;
});
});
});
casper.waitFor(function() {
return this.evaluate(function() {
return window.siteLoaded === true;
});
});
casper.then(function() {
// process further
});
Note: this is factice pseudo code, purpose is only to picture the concept.

Click button on load event

I have the following javascript -
function onLoad() {
if (!(document.applets && document.VLVChart && document.VLVChart.isActive())) {
setTimeout('onLoad()', 200);
return;
}
objChart = document.VLVChart;
PollEvent();
}
function fan() {
objChart.reorganize();
}
And then when the HTML page is loaded -
<body onLoad="onLoad()">
and have a button within the HTML that execute the fan() function -
<input type='button' value='Fan' onClick='fan();'>
Is it possible for me to activate the fan() function within the onload event so that a user does ont have to click the button?
EDIT
After trying the provided answers, on debugging the code breaks on the line -
objChart.reorganize();
Within the fan() function with the error -
SCRIPT5007: Unable to get value of the property 'reorganize': object is null or undefined
This is odd as when I manually click the button on the page, the function works fine.
Solution
After much head scratching I have realised that I was trying to load the fan() function before the page (and more specifically the objChart) had fully loaded. Hence why adding the function in the onLoad event was not working. I added a setTimeout -
function Fan()
{
setTimeout(function(){objChart.reorganize();},3000);
}
<body onload='onLoad(); fan();'>...
However inline JS is best avoided and you would do well to begin looking into centralised event management. There are various advantages to this.
An answer I wrote yesterday to another question outlines why this is. Something like jQuery makes this trivial if it's new for you.
$(function() {
$('body').on('load', function() {
onLoad();
fan();
});
});
Reading your question I assume you didn't even have tried. Just call that function from within your onLoad()-function:
function onLoad()
{
fan();
/* … */
}
Yes.
You can use <body onload='onLoad(); fan();'> as Utkanos suggests.
If you use jQuery, you can also stick a script in the head containing:
$(function(){
...
});
The jQuery function actually fires earlier, as is explained here.

jquery call to javascript function inside LIVE Never occurs

I am doing an AJAX call that returns some HTML and jQuery:
<div id='selected'>Here is my Selection Text
<a id='trashSelected' href=\"javascript:void(0);\">Remove</a>
</div>
<script>
$('#trashSelected').live('click',function delete()
{
// remove the container
$('#selected').remove();
substractSelectionCount();
return false;
});
</script>
The jQuery removes the container that was added if the user clicks on the link "Remove".
It does the job removing the container, but the call to substractSelectionCount(); never occurs. should I be doing the call to this function in a different way?
This is a function that was already in the document. Tested in FF, IE 8 and Safari
I might be missing something, but have you tried it this way?
$('#trash{$roleId}').live('click',function delete()
{
// remove the container
substractSelectionCount();
$('#selected').remove();
return false;
});
There seems to be a syntax error in your function callback remove the word delete
$('#trash{$roleId}').live('click',function(e) {
e.preventDefault();
alert('trash clicked');
// ...
return false;
});
A work around for this problem is: instead of returning script from the ajax call, I use classes in my main file. All the response returns is this string
<div id='selected'>Here is my Selection Text
<a class='trashSelected' href=\"javascript:void(0);\">Remove</a>
</div>
and in my file I have a function like this
$('.trashSelected').live('click',function(){
$(this).parent().remove();
subtractSelectionCount();
return false;
});
Is your currentSelectionCount a global variable? Maybe the function is being called and it's not working because of this?
And did you try adding an alert into the function to make sure it's not being called?
function substractSelectionCount(){
alert("I'm working!");
currentSelectionCount--;
}
I put together a test file in this pastebin and it appeared to be working perfectly with IDs... but since I added three divs to test it I had to replace the IDs with classes. So, I'm not sure where your code is having problems - maybe your substractSelectionCount function is outside of the document.ready function?

Categories