2

I have image library that is provisioned by publishing feature, I added the view of this library to the page which contains my custom web part with jQuery

enter image description here

After this I have an error

TypeError: $(...).attr is not a function

on line

var attrValue = $(this).attr('attrName'); 

Without images view web part works correctly. How can I solve this issue?

3
  • Post your Jquery so we can have a look mate. Commented Jan 8, 2013 at 15:28
  • How did you referenced jQuery? Did you wrap your code within a $(function() { .... }); block? Commented Jan 8, 2013 at 16:22
  • @Fox and SteveB, js code works prefect if page does not contain view of image library. This code is invoked into '$(document).ready(function() {})', I've binded event for span element. I've added jQuery through ScriptLink server tag. Commented Jan 8, 2013 at 16:34

1 Answer 1

2

This is most likely caused because of conflicts with the selector $ used in JavaScript libraries for SharePoint, which uses the same variable as the jQuery selector.

General recommendation: Always use jQuery’s noConflict() method in SharePoint

For example:

var $j = jQuery.noConflict(); $j(function() { $j("a").click(function(e){ var hrefVal = $j(this).attr('href'); console.log(hrefVal); }); }); 
4
  • Thanks! One additional question - could you tell me some best practice how to use jQuery for SharePoint? as I understand the code from your answer have to be included in any custom web part. Am I right? Commented Jan 9, 2013 at 8:42
  • It actually depends, for the scenario when you create jQuery enabled web parts: 1) deploy JavaScript files for web parts into hive 2) reference it in web parts (provide reference to js file(s) in Render() method for Web Parts, for Visual web parts in ASCX User Control). Regarding code from example, yes, it could be reused, but i suggest not to embed it directly into web part, but to create separate js file and reference it in web part Commented Jan 9, 2013 at 10:24
  • 1
    Also, dont ever use the Jquery event binding for body onload. Its going to cause problems with Sharepoint. You should always use This Function (built in SP Function) to load your custom scripts: ExecuteOrDelayUntilScriptLoaded(checkJQuery, 'SP.UI.MyLinksRibbon.js'); Read more here : blog.fidelityfactory.com/2012/04/03/when-to-load-my-ecma-script Commented Jan 9, 2013 at 11:27
  • Can't you just replace $ with jQuery rather than declaring the $j variable? Commented Jul 1, 2015 at 15:11

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.