jQuery Function Not Working on document load - javascript

I've got a jQuery function that usually works on a Volusion page and for some reason now it's not working. The location.pathname.indexOf targets all pages that have that URL (the site uses GET variables to do searches on the SearchResults.asp page). I've changed the quotations from singles to doubles and I can't seem to figure out anything else to do test it. Does anyone see any syntax errors in this code? There shouldn't be any conflicts since it's only running jQuery (and nothing else like MooTools). I tried to also do an alert of 'Test' after document.ready but nothing happened on the screen. Thanks!
<script>
$(document).ready(function() {
if (location.pathname.indexOf('/SearchResults.asp') != -1 ) {
$('div#content_area').css({'display','none !important'});
}
});
</script>

You have a syntax error.
This:
$('div#content_area').css({'display', 'none !important'});
Should be this:
$('div#content_area').css({'display': 'none !important'});
// ^
// |
// | look here
When using .css() you can use 2 variations.
You can either use it to update a single property which uses the , to separate the name of the CSS property and the value, similar to this:
$('div#content_area').css('display', 'none !important');
Or you can use the new variation, added in jQuery 1.9 which allows you specify multiple styles at once allowing you to specify property-value pairs, similar to this:
$('div#content_area').css({
'display': 'none !important',
'border' : 'solid 1px red'
});
css() and !important
There seems to be an issue when trying to apply a style using .css() and !important.
there is a bug which was raised a long time ago: The Ticket #2066 which was closed and an alternative was shown in that ticked.
It mentions that as an alternative you can set the cssText similar to this when using the multi-style variation:
$('div#content_area').css({
'cssText': 'display: none !important'
});
or this when using the single style variation:
$('div#content_area').css('cssText', 'display: none !important');
Though, as the ticked mentions, a word of caution:
You have to be careful setting cssText since it sets/clears everything
in the css for that element.
Another alternative, which most likely is the safest given the side-effects of cssText, is to create a separate CSS class and apply that, similar to this:
.alwaysHide{
display: none !important;
}
$('div#content_area').addClass('alwaysHide');
Hope this helps.

You are trying to use 2 syntax styles.
Either, you need to do this:
<script>
$(document).ready(function() {
if (location.pathname.indexOf('/SearchResults.asp') != -1 ) {
$('div#content_area').css('display','none !important');
}
});
</script>
or you need to use this:
<script>
$(document).ready(function() {
if (location.pathname.indexOf('/SearchResults.asp') != -1 ) {
$('div#content_area').css({'display' : 'none !important'});
}
});
</script>

Related

Parameterize jQuery addClass?

Is it somehow possible to parameterize the jQuery addClass() method?
Like, having a css class with a color property which is set when the addClass() method is called?
I hope that makes sense as I am very new to JavaScript and CSS. If it's of importance, I'm working on extending the MediaWiki VisualEditor. There this method is used to immediatly show/render changes made in the editor. But I couldn't find an example which would require parameterization.
If it's not possible, I'd love to know how to do it.
If it's not, maybe someone can suggest how to realize what I want another way?
Edit:
That's the current state:
When I add some annotation to the text, let's say a languageAnnotation, this is called:
this.$element
.addClass( 've-ce-languageAnnotation' )
.addClass( 've-ce-bidi-isolate' )
.prop( {
lang: this.model.getAttribute( 'lang' ),
dir: this.model.getAttribute( 'dir' ),
title: this.constructor.static.getDescription( this.model )
} );
This is ve-ce-languageAnnotation:
.ve-ce-languageAnnotation {
border-bottom: 1px dashed #ccc;
background-color: #ebf3f5;
}
This is ve-ce-bidi-isolate:
.ve-ce-bidi-isolate {
unicode-bidi: isolate;
unicode-bidi: -moz-isolate;
unicode-bidi: -webkit-isolate;
}
I interpreted this as the prop() function setting some kind of parameter. So this is what I tried for my textColor annotation:
this.$element
.addClass( 've-ce-textColorAnnotation' )
.prop( {
color: this.model.getAttribute( 'style' ),
title: this.constructor.static.getDescription( this.model )
} )
;
With ve-ce-TextColorAnnotation:
.ve-ce-textColorAnnotation {
color: red;
}
This always produces red. When I try to enter something else then a legit color, nothing happens.
Edit2: I guess one option would be to create a class for each possible color, and adding the right class depending on the parameter? Like this:
var color = this.model.getAttribute('style');
if (color == 'blue') {
this.$element.addClass( 'blueText' )
} else if (...
but that doesn't look like a really good idea.
Edit 3: According to the top answer in this question, what I want is not possible - but I can directly apply an attribute without using classes by using this.$element.css('attr', 'value'). I guess I can use this for what I need.
It appears you simply want to set a color, rather than add a class. Classes in HTML can be used for stylization or DOM navigation, however in your case you simply want to apply a different color to an element. You don't need to use classes for that, especially if the colors are dynamic.
What you want to do is call jquery's .css() method. It can be used with a single argument like so:
element.css({
'color': 'black',
'height': '100px'
});
or several, if you only want to edit a single property:
element.css('color', 'black');
Without using jQuery, you could also do this:
element.style.color = 'black';
What can you do in a simple way. Let's say you have a drop down from which you chose the colors. On the value attribute of the option you have blueText for blue, redText for red and so on for each color you want.
Then on the code you can get the value. You can see here how to get the value then you have the classes in CSS like redText, blueText and so on.
When the user clicks on the option you catch the event and do this simple pice of code:
this.$element.addClass( 'text that you got from value attribute' )
You can of course remove the classes before you do the add.

Jquery change background size AND image src

I'm trying to change both background-image and background-size (so it fits the div)
$(".clickableimg").click(function() {
var choosenpic = $(this).attr('id');
$("#image").val(choosenpic);
$("#preview").css("background","url(backgrounds/"+choosenpic+")");
$("#preview").css("background","size('50%')");
});
Do you know how I can change more css attributes?
Setting the background style twice overwrites it, so only the last one will stick, you'll need to use valid CSS properties, like background-image and background-size to change them seperately :
$(".clickableimg").on('click', function() {
var choosenpic = this.id;
$("#image").val(choosenpic);
$("#preview").css({
'background-image' : 'url(backgrounds/'+choosenpic+')',
'background-size' : '50%'
});
});
I'm not entirely sure that your code works correctly because I think you mean
$("#preview").css("background-image","url(backgrounds/"+choosenpic+")");
but if what you have works already then cheers.
You can change any css attributes as long as its supported by the browser.
$("#preview").css("display", "none")
$("#preview").css("width", "5000px")
$("#preview").css("text-shadow", "...")
$("#preview").css("box-shadow", "...")
$("#preview").css("border", "...") ..
I can go on and on..but here is a list of some of CSS3 properties you can play with
http://www.quackit.com/css/css3/properties/
First of all if you're new to javascript you should first look at how javascript basically works before starting with a framework like jQuery. According to your question the following jquery plugin should help you to accomplish your task:
https://github.com/louisremi/background-size-polyfill
This plugin will help you get it working in IE8 too.

JS IE8, 7, 9 Error 'attr(..)' is null or not an object

I want to show the box-shadow when div is expanded. I am adding a class which is having a box-shadow class in expanding div case.
And it is working fine in all the browsers.
Problem what I am facing is IE 8 is showing an error :- 'attr(...)' is null or not an object.
I need your help to fix this. Please suggest.
This is what I have done:
<script type="text/javascript">
animatedcollapse.addDiv('navDrop', 'fade=0,speed=100,')
animatedcollapse.addDiv('needHelp', 'fade=10,speed=300,')
animatedcollapse.ontoggle=function($, divobj, state){ //fires each time a DIV is expanded/contracted
//$: Access to jQuery
//divobj: DOM reference to DIV being expanded/ collapsed. Use "divobj.id" to get its ID
//state: "block" or "none", depending on state
jkmegamenu.render($);
if($(".needHelpBox").attr('class').indexOf("shadow") > 0)
{
$(".needHelpBox").attr('class',$(".needHelpBox").attr('class').replace("shadow",""));
}
else
{
$(".needHelpBox").addClass('shadow');
}
}
animatedcollapse.init()
</script>
Please help..!
Thanks
You're using jQuery! Use the methods that are here for you:
var helpBox = $(".needHelpBox");
if(helpBox.hasClass('shadow')){
helpBox.removeClass('shadow');
} else {
helpBox.addClass('shadow');
}
Bergi's solution is even simpler as it takes advantage of the toggleClass method.
The problem you're facing might also be within the selector $(".needHelpBox")
Are you sure the html element has the right class (needHelpBox) attribute?
And what version of jQuery are you using?
It seems you want to use the toggleClass() method (if you use jQuery):
$(".needHelpBox").toggleClass("shadow");
or the toggleClassName method (you use Prototype, which seems likelier when there is no attr):
$(".needHelpBox").toggleClassName("shadow");

CodeMirror 2 - Highlight only (no editor)

Can CodeMirror 2 be used to highlight code from a DIV or PRE tag (without the editor)?
Like CodeMirror 1 used to be able to do with the hightlightText() function?
For example here: http://codemirror.net/1/highlight.html, after you press run highlight (the highlighted text below)
Also can it highlight code from a inline element, like <code>, and keep the results inline, like Google's Prettify does?
A much nicer and easier solution is to just set the readOnly property of the CodeMirror instance to true, like this:
$('.code').each(function() {
var $this = $(this),
$code = $this.html();
$this.empty();
var myCodeMirror = CodeMirror(this, {
value: $code,
mode: 'javascript',
lineNumbers: !$this.is('.inline'),
readOnly: true
});
});
Just add the class .code to the tag containing the code and it will be syntax highlighted. I've also added support for inline code, by using the class .inline.
Example on jsfiddle
As a somewhat late update, CodeMirror 2 recently gained this ability. See http://codemirror.net/demo/runmode.html
You should use a standalone code syntax highlighter: SyntaxHighlighter 3 works really well.
If you really want CodeMirror, there is a readOnly option:
var myCodeMirror = CodeMirror(function(elt) {
myElement.parentNode.replaceChild(myElement, elt); // myElement is your <pre> or <div>
}, {
value: myElement.value,
readOnly: true
});
Actually you can't. Codemirror2 is written in the way that all implementation is hidden in closures. Public methods which can be used are described in documentation http://codemirror.net/manual.html
The only available options are to use anothe syntax highlighters or dive into the code of CodeMirror2 to strip necessary parts out.
If you will chose last option, please give attention to
function refreshDisplay(from, to) method
it loops through lines and highlights them.
Edit
Just realized a simpler method exists. Read method 2 below. I'm keeping the old method and its explanations intact and just include the improved jQuery code.
If you are asking about a native method of the package, the answer is no, it only works with textarea. But if you are open to using workarounds, here is one that works (tested).
I have used jQuery here, but its use is not a must and you can achieve the same with pure js code, though it would be longer and not as neat as jQuery code.
Now, let's get to the workaround.
Suppose you have a <pre> with code inside, that you want to turn into editor-less syntax-highlighted codemirror container:
<pre id="mycode">
<?php
echo 'hi';
$a = 10;
if($a == 5) echo 'too small';
?>
</pre>
What you do is,
change the <pre> to <textarea>,
attach codemirror to the textarea,
hide the fake cursor and keep it hidden, and
do not allow the hidden codemirror's textarea grab the focus (and snatch it back when it does).
For the last action I have used the method suggested by Travis Webb. Here is the jQuery code that does these four things:
$(document).ready(function() {
// (1) replace pre with textarea
$('#mycode').replaceWith('<textarea id="code">' + $('#mycode').html() + '</textarea>');
// (2) attach codemirror
var editor = CodeMirror.fromTextArea($("#code"), {
lineNumbers: true,
mode: "application/x-httpd-php"
});
// (3) hide the fake cursor
$('pre.CodeMirror-cursor').hide();
// [4] textarea to grab and keep the focus
$('body').append('<textarea id="tricky" style="height: 1px; position: fixed; width: 1px; top: 0; margin-top: -100px;" wrap="off"></textarea>');
// (4) grab focus
$('#tricky').focus();
// [4] if focus is lost (probably to codemirror)
$('#tricky').blur(function() {
// (4) re-claim focus
$('#tricky').focus();
// (3) keep the fake cursor hidden
$('pre.CodeMirror-cursor').hide();
});
});
Method Two
Instead of wrestling with cursor and all that, we can remove the elements that make the editor tick. Here is the code:
$(document).ready(function() {
$('#mycode').replaceWith('<textarea id="code">' + $('#mycode').html() + '</textarea>');
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "application/x-httpd-php"
});
$('pre.CodeMirror-cursor').remove();
$('div.CodeMirror').find('textarea').blur().parent().remove();
$('div.CodeMirror').find('pre:first').remove();
$('textarea#code').remove();
});
CodeMirror V2 contains a runmode.js.
I've wrote an example using runmode with gutter.
check:
http://jsfiddle.net/lyhcode/37vHL/2/
Heres an simpler solution using codemirror runmode and jquery:
<pre class='code'>{:message => 'sample code'}</pre>
$(document).ready(function() {
$('.code').each(function(index, e) {
$(e).addClass('cm-s-default'); // apply a theme class
CodeMirror.runMode($(e).text(), "javascript", $(e)[0]);
});
});

Switching between two different classes jQuery

Having trouble getting the following code to work:
$('#changeMode').button().click(function(){
$('#playfield').toggle(function() {
$(this).switchClass("gridView","plainView");
}, function() {
$(this).switchClass("plainView","gridView");
});
});
I cannot get it to switch the following div's class.
<div id="playfield" class="gridView"></div>
Any ideas?
EDIT: I tried this:
$('#changeMode').button().click(function(){
if ($('#playfield').attr('class') == "gridView"){
$('#playfield').removeClass("gridView");
$('#playfield').addClass("plainView");
} else {
$('#playfield').removeClass("plainView");
$('#playfield').addClass("gridView");
}
});
And it seems to work fine, what the heck?
I wasn't aware of a switchClass, perhaps you were thinking of toggleClass? Anyways - I had some old code that used this (I was having some strange issues with toggleClass):
$(this).removeClass("gridView").addClass("plainView");
or
$(this).toggleClass("gridView plainView");
and vice versa.
Example:
$('#changeMode').button().click(function(){
$('#playfield').toggle(function() {
$(this).toggleClass("gridView plainView");
//$(this).removeClass("gridView").addClass("plainView");
}, function() {
$(this).toggleClass("plainView gridView");
//$(this).removeClass("plainView").addClass("gridView");
});
});
But as others have suggested toggleClass should work for your needs.
The correct syntax is to use "One or more class names (separated by spaces).." ( from .toggleClass()) within the first parameter, rather than quoting classnames in the first and second parameter.
e.g.
$(this).toggleClass("gridView plainView");
just use the toggleClass twice will do the magic . toggoleClass refference to Jquery
This method takes one or more class names as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added.
as for ur problem .
$('#changeMode').button().click(function(){
$(this).toggleClass('gridView').toggleClass('plainView');
});
help this will solve ur problem .
#Guy toggleClass('gridView plainView') this will actually be alternates bettween
<div class="gridView plainView"> and <div class=" ">. and not toggle bettween the two classe . no offence . hope this will do some help .
jQuery also has a toggleClass API:
http://api.jquery.com/toggleClass/
This works just like what Rionmonster suggested, adding classes when they aren't set on the class and removing them when they are already set.

Categories

Resources