Embed JS code in body field - drupal

Doesn't Drupal 7 block javascript code in body field of the node? I use filter "Full HTML" and still it doesn't work. Maybe I don't load it right, here it is:
$(document).ready(function(){
$('.text-block:gt(0)').hide();
setInterval(function(){
$('#text-blocks > :first-child').fadeOut(0)
.next().fadeIn(0)
.end()
.appendTo('#text-blocks');
},
3000);

I know that when putting jQuery into drupal fields, you have to wrap them in script and jquery tags.
<script>
(function ($) {
// Original JavaScript code.
})(jQuery);
</script>

It would probably be best to enable the PHP filter if you can. Enable that in the modules section and use it for that specific block.
If you are using a WYSIWYG, you would have to switch it to plain text for the javascript to work.

I don't know mechanisms of displaying nodes in drupal but when i removed $(document).ready(function(){ from my script, it started to work fine.

Related

Why do my MVC application gives errors on a cloud server? [duplicate]

I have a simple jquery click event
<script type="text/javascript">
$(function() {
$('#post').click(function() {
alert("test");
});
});
</script>
and a jquery reference defined in the site.master
<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>
I have checked that the script is being resolved correctly, I'm able to see the markup and view the script directly in firebug, so I must be being found. However, I am still getting:
$ is not defined
and none of the jquery works. I've also tried the various variations of this like $(document).ready and jQuery etc.
It's an MVC 2 app on .net 3.5, I'm sure I'm being really dense, everywhere on google says to check the file is referenced correctly, which I have checked and checked again, please advise! :/
That error can only be caused by one of three things:
Your JavaScript file is not being properly loaded into your page
You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.
You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.
First of all, ensure, what script is call properly, it should looks like
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
and shouldn't have attributes async or defer.
Then you should check the Firebug net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say "404" beside it. If the file is loading properly, that means that the issue is number 2.
Make sure all jQuery javascript code is being run inside a code block such as:
$(document).ready(function () {
//your code here
});
This will ensure that your code is being loaded after jQuery has been initialized.
One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.
Note: If you're loading code which does not require jQuery to run it does not need to be placed inside the jQuery ready handler. That code may be separated using document.readyState.
It could be that you have your script tag called before the jquery script is called.
<script type="text/javascript" src="js/script.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
This results as $ is not defined
Put the jquery.js before your script tag and it will work ;) like so:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/script.js"></script>
First you need to make sure that jQuery script is loaded. This could be from a CDN or local on your website. If you don't load this first before trying to use jQuery it will tell you that jQuery is not defined.
<script src="jquery.min.js"></script>
This could be in the HEAD or in the footer of the page, just make sure you load it before you try to call any other jQuery stuff.
Then you need to use one of the two solutions below
(function($){
// your standard jquery code goes here with $ prefix
// best used inside a page with inline code,
// or outside the document ready, enter code here
})(jQuery);
or
jQuery(document).ready(function($){
// standard on load code goes here with $ prefix
// note: the $ is setup inside the anonymous function of the ready command
});
please be aware that many times $(document).ready(function(){//code here}); will not work.
If the jQuery plugin call is next to the </body>, and your script is loaded before that, you should make your code run after window.onload event, like this:
window.onload = function() {
//YOUR JQUERY CODE
}
`
so, your code will run only after the window load, when all assets have been loaded. In that point, the jQuery ($) will be defined.
If you use that:
$(document).ready(function () {
//YOUR JQUERY CODE
});
`
the $ isn't yet defined at this time, because it is called before the jQuery is loaded, and your script will fail on that first line on console.
I just did the same thing and found i had a whole lot of
type="text/javacsript"
So they were loading, but no further hint as to why it wasn't working. Needless to say, proper spelling fixed it.
Use a scripts section in the view and master layout.
Put all your scripts defined in your view inside a Scripts section of the view. This way you can have the master layout load this after all other scripts have been loaded. This is the default setup when starting a new MVC5 web project. Not sure about earlier versions.
Views/Foo/MyView.cshtml:
// The rest of your view code above here.
#section Scripts
{
// Either render the bundle defined with same name in BundleConfig.cs...
#Scripts.Render("~/bundles/myCustomBundle")
// ...or hard code the HTML.
<script src="URL-TO-CUSTOM-JS-FILE"></script>
<script type="text/javascript">
$(document).ready(function () {
// Do your custom javascript for this view here. Will be run after
// loading all the other scripts.
});
</script>
}
Views/Shared/_Layout.cshtml
<html>
<body>
<!-- ... Rest of your layout file here ... -->
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
Note how the scripts section is rendered last in the master layout file.
It means that your jQuery library has not been loaded yet.
You can move your code after pulling jQuery library.
or you can use something like this
window.onload = function(){
// Your code here
// $(".some-class").html("some html");
};
As stated above, it happens due to the conflict of $ variable.
I resolved this issue by reserving a secondary variable for jQuery with no conflict.
var $j = jQuery.noConflict();
and then use it anywhere
$j( "div" ).hide();
more details can be found here
make sure you really load jquery
this is not jquery - it's the ui!
<script language="JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js">
</script>
This is a correct script source for jquery:
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
Are you using any other JavaScript libraries? If so, you will probably need to use jQuery in compatibility mode:
http://docs.jquery.com/Using_jQuery_with_Other_Libraries
after some tests i found a fast solution ,
you can add in top of your index page:
<script>
$=jQuery;
</script>
it work very fine :)
I had the same problem and resolved it by using
document.addEventListener('DOMContentLoaded', () => {
// code here
});
I got the same error message when I misspelled the jQuery reference and instead of type="text/javascript" I typed "...javascirpt". ;)
It sounds like jQuery isn't loading properly. Which source/version are you using?
Alternatively, it could a be namespace collision, so try using jQuery explicitly instead of using $. If that works, you may like to use noConflict to ensure the other code that's using $ doesn't break.
That error means that jQuery has not yet loaded on the page. Using $(document).ready(...) or any variant thereof will do no good, as $ is the jQuery function.
Using window.onload should work here. Note that only one function can be assigned to window.onload. To avoid losing the original onload logic, you can decorate the original function like so:
originalOnload = window.onload;
window.onload = function() {
if (originalOnload) {
originalOnload();
}
// YOUR JQUERY
};
This will execute the function that was originally assigned to window.onload, and then will execute // YOUR JQUERY.
See https://en.wikipedia.org/wiki/Decorator_pattern for more detail about the decorator pattern.
I use Url.Content and never have a problem.
<script src="<%= Url.Content ("~/Scripts/jquery-1.4.1.min.js") %>" type="text/javascript"></script>
In the solution it is mentioned -
"One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described."
For avoiding this -
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict():
I had this problem once for no apparent reason. It was happenning locally whilst I was running through the aspnet development server. It had been working and I reverted everything to a state where it had previously been working and still it didn't work. I looked in the chrome debugger and the jquery-1.7.1.min.js had loaded without any problems. It was all very confusing. I still don't know what the problem was but closing the browser, closing the development server and then trying again sorted it out.
Just place jquery url on the top of your jquery code
like this--
<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#post').click(function() {
alert("test");
});
});
</script>
I had the same problem and it was because my reference to the jQuery.js was not in the tag. Once I switched that, everything started working.
Anthony
Check the exact path of your jquery file is included.
<script src="assets/plugins/jquery/jquery.min.js"></script>
if you add this on bottom of your page , please all call JS function below this declaration.
Check using this code test ,
<script type="text/javascript">
/***
* Created by dadenew
* Submit email subscription using ajax
* Send email address
* Send controller
* Recive response
*/
$(document).ready(function() { //you can replace $ with Jquery
alert( 'jquery working~!' );
});
Peace!
This is the common issue to resolve this you have to check some point
Include Main Jquery Library
Check Cross-Browser Issue
Add Library on TOP of the jquery code
Check CDNs might be blocked.
Full details are given in this blog click here
I came across same issue, and it resolved by below steps.
The sequence of the scripts should be as per mentioned below
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
This sequence was not correct for my code, I corrected this as per the above and it resolved my issue of Jquery not defined.
We have the same problem....but accidentally i checked folder properties and set something...
You have to check the properties of each folders that you're accessing..
right click folder
'permissions' tab
set the folder access :
OWNER: create and delete files
GROUP: access files
OTHERS: access files
I hope that this is the solution......
When using jQuery in asp.net, if you are using a master page and you are loading the jquery source file there, make sure you have the header contentplaceholder after all the jquery script references.
I had a problem where any pages that used that master page would return '$ is not defined' simply because the incorrect order was making the client side code run before the jquery object was created. So make sure you have:
<head runat="server">
<script type="text/javascript" src="Scripts/jquery-VERSION#.js"></script>
<asp:ContentPlaceHolder id="Header" runat="server"></asp:ContentPlaceHolder>
</head>
That way the code will run in order and you will be able to run jQuery code on the child pages.
In my case I was pointing to Google hosted JQuery. It was included properly, but I was on an HTTPS page and calling it via HTTP. Once I fixed the problem (or allowed insecure content), it fired right up.
After tried everything here with no result, I solved the problem simply by moving the script src tag from body to head
I was having this same problem and couldn't figure out what was causing it. I recently converted my HTML files from Japanese to UTF-8, but I didn't do anything with the script files. Somehow jquery-1.10.2.min.js became corrupted in this process (I still have no idea how). Replacing jquery-1.10.2.min.js with the original fixed it.
it appears that if you locate your jquery.js files under the same folder or in some subfolders where your html file is, the Firebug problem is solved. eg if your html is under C:/folder1/, then your js files should be somewhere under C:/folder1/ (or C:/folder1/folder2 etc) as well and addressed accordingly in the html doc. hope this helps.
I have the same issue and no case resolve me the problem. The only thing that works for me, it's put on the of the Site.master file, the next:
<script src="<%= ResolveUrl("~/Scripts/jquery-1.7.1.min.js") %>" type="text/javascript"></script>
<script src="<%= ResolveUrl("~/Scripts/bootstrap/js/bootstrap.min.js") %>" type="text/javascript"></script>
With src="<%= ResolveUrl("")... the load of jQuery in the Content Pages is correct.

simple script to apply bootstrap pagination style in asp.net gridview

is there any simple jquery script/plugin to apply bootstrap pagination style in asp.net gridview ? I've found some good tips about how to do this, like these links: here and here.
the only problem with these tips/solutions is we need to make a lot of changes to achieve the result and this is not preferable when you have large application and you want to transform it to bootstrap style. we need another solution. like a simple jquery script that can do the job without making lot changes to the current code.
I've made simple jquery script to apply the bootstrap pagination in asp.net gridview and I think it will be useful to share it here in stackoverflow.
source code of this script is hosted in github here.
usage is very simple:
-include the plugin js file in your asp.net page file:
<script type="text/javascript" src="js/bs.pagination.js"></script>
-set gridview property:
PagerStyle-CssClass="bs-pagination"
that's is all you need to apply bootstrap pagination style in asp.net gridview.
check my blog for more info.
Edit:
about the problem when using gridview inside UpdatePanel, the reason of this problem is because “UpdatePanel completely replaces the contents of the update panel on an update. This means that those events we subscribed to are no longer subscribed because there are new elements in that update panel.”
There is more than one solution to solve this problem:
Solution 1:
Use pageLoad() instead of $(document).ready. Modify the code like this:
function pageLoad() {
$('.bs-pagination td table').each(function (index, obj) {
convertToPagination(obj)
});
}
Solution2:
re-change the style after every update. We can do this by adding these lines to the bs.pagination.js file:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
$('.bs-pagination td table').each(function (index, obj) {
convertToPagination(obj)
});
});

Drupal jQuery noConflict - working for alert by not css change

Im using the jQuery noConflict method here:
http://drupal.org/node/1058168
Now, both of the following work:
$jq("document").ready(function(){
alert('alert');
});
$("document").ready(function(){
alert('alert');
});
However this does work:
$("document").ready(function(){
$(".view-product-slideshow .pager-num-1 img").css("display","none");
});
But this does not:
$jq("document").ready(function(){
$jq(".view-product-slideshow .pager-num-1 img").css("display","none");
});
Ive used the noConflict method once before and it worked fine. Ive no idea why it would work for the alert but not the CSS change.
My site is here:
http://smartpeopletalkfast.co.uk/pp4/shop/baby-essentials/sleepsuit-plush
Thanks
UPDATE - Ive now removed the extra code from script.js so all thats there is:
//Hide thumnail on product page thats being used as main image
$jq("document").ready(function(){
$jq(".view-product-slideshow .pager-num-1 img").css("display","none");
});
your error is on line 61 of ur script.js:
Uncaught TypeError: Object #
has no method 'smoothDivScroll'
also in that file u should have everything wrapped in the .ready() not every individual thing
Turns out the element I was trying to target with jQuery was itself generated by javascript. Changing my document.ready to window.load fixed this.
When using the noconflict mode of jQuery, you should use this:
jQuery(document).ready(function($){
$(".view-product-slideshow .pager-num-1 img").css("display","none");
});
jQuery is the new $ and you can pass jQuery as $ to your function().
Also, it's document and not "document"

jQuery and asp.net not playing nice together

Please refer to this page for reference: http://loadedgranola.valitics.com/_product_83484/blackberry_lime
I have a jQuery script that runs to replace the h1 tags with a background image. It works great when the document loads but when I click "add to cart", after the javascript alert the jQuery styling breaks. Due to CMS restrictions I have no direct access to their javascript or any of the ASP files but I assume there has to be an easy fix to this.
The code I'm using:
jQuery(document).ready(function(){
var textReplacer = document.title.replace(/ /g,'');
jQuery("h1").addClass('replaced').css("background","url(../images/h1/" + textReplacer + ".png) no-repeat 0 0");
});
I have also tried using the function pageLoad(sender, args) { magic but no luck.
Here you go ..
jQuery(document).ready( function() {
jQuery('<style type="text/css" media="screen">h1{text-indent:-9999px!important;background:url(../images/h1/'+document.title.replace(/ /g,'') +'.png) no-repeat 0 0!important;}</style>').appendTo('head');
});
what it does is add a new css rule that pushes the text way out of the box and adds the background image
Here is what is happening:
When you submit the shopping cart it's doing an AJAX call. The result of that call replaces most of the HTML on the page. Any changes you made before that get replaced.
Possible Solution
You would have to run that replace script again after the AJAX call is complete.
Questions
Why are you replacing the H1 tags on load? What problem are you trying to solve? You might be able to find a better CSS solution.

Using CSS to affect div style inside iframe

Is it possible to change styles of a div that resides inside an iframe on the page using CSS only?
You need JavaScript. It is the same as doing it in the parent page, except you must prefix your JavaScript command with the name of the iframe.
Remember, the same origin policy applies, so you can only do this to an iframe element which is coming from your own server.
I use the Prototype framework to make it easier:
frame1.$('mydiv').style.border = '1px solid #000000'
or
frame1.$('mydiv').addClassName('withborder')
In short no.
You can not apply CSS to HTML that is loaded in an iframe, unless you have control over the page loaded in the iframe due to cross-domain resource restrictions.
Yes. Take a look at this other thread for details:
How to apply CSS to iframe?
const cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['frame1'].contentWindow.document.body.appendChild(cssLink);
// ^frame1 is the #id of the iframe: <iframe id="frame1">
You can retrieve the contents of an iframe first and then use jQuery selectors against them as usual.
$("#iframe-id").contents().find("img").attr("style","width:100%;height:100%")
$("#iframe-id").contents().find("img").addClass("fancy-zoom")
$("#iframe-id").contents().find("img").onclick(function(){ zoomit($(this)); });
Good Luck!
The quick answer is: No, sorry.
It's not possible using just CSS. You basically need to have control over the iframe content in order to style it. There are methods using javascript or your web language of choice (which I've read a little about, but am not to familiar with myself) to insert some needed styles dynamically, but you would need direct control over the iframe content, which it sounds like you do not have.
Use Jquery and wait till the source is loaded,
This is how I have achieved(Used angular interval, you can use javascript setInterval method):
var addCssToIframe = function() {
if ($('#myIframe').contents().find("head") != undefined) {
$('#myIframe')
.contents()
.find("head")
.append(
'<link rel="stylesheet" href="app/css/iframe.css" type="text/css" />');
$interval.cancel(addCssInterval);
}
};
var addCssInterval = $interval(addCssToIframe, 500, 0, false);
Combining the different solutions, this is what worked for me.
$(document).ready(function () {
$('iframe').on('load', function() {
$("iframe").contents().find("#back-link").css("display", "none");
});
});
Apparently it can be done via jQuery:
$('iframe').load( function() {
$('iframe').contents().find("head")
.append($("<style type='text/css'> .my-class{display:none;} </style>"));
});
https://stackoverflow.com/a/13959836/1625795
probably not the way you are thinking. the iframe would have to <link> in the css file too. AND you can't do it even with javascript if it's on a different domain.
Not possible from client side . A javascript error will be raised "Error: Permission denied to access property "document"" since the Iframe is not part of your domaine.
The only solution is to fetch the page from the server side code and change the needed CSS.
A sort of hack-ish way of doing things is like Eugene said. I ended up following his code and linking to my custom Css for the page. The problem for me was that, With a twitter timeline you have to do some sidestepping of twitter to override their code a smidgen. Now we have a rolling timeline with our css to it, I.E. Larger font, proper line height and making the scrollbar hidden for heights larger than their limits.
var c = document.createElement('link');
setTimeout(frames[0].document.body.appendChild(c),500); // Mileage varies by connection. Bump 500 a bit higher if necessary
Just add this and all works well:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
If the iframe comes from another server, you will have CORS ERRORS like:
Uncaught DOMException: Blocked a frame with origin "https://your-site.com" from accessing a cross-origin frame.
Only in the case you have control of both pages, you can use https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage to safely send messages like this:
On you main site(one that loads the iframe):
const iframe = document.querySelector('#frame-id');
iframe.contentWindow.postMessage(/*any variable or object here*/, 'https://iframe-site.example.com');
on the iframe site:
// Called sometime after postMessage is called
window.addEventListener("message", (event) => {
// Do we trust the sender of this message?
if (event.origin !== "http://your-main-site.com")
return;
...
...
});
Yes, it's possible although cumbersome. You would need to print/echo the HTML of the page into the body of your page then apply a CSS rule change function. Using the same examples given above, you would essentially be using a parsing method of finding the divs in the page, and then applying the CSS to it and then reprinting/echoing it out to the end user. I don't need this so I don't want to code that function into every item in the CSS of another webpage just to aphtply.
References:
Printing content of IFRAME
Accessing and printing HTML source code using PHP or JavaScript
http://www.w3schools.com/js/js_htmldom_html.asp
http://www.w3schools.com/js/js_htmldom_css.asp

Resources