Having trouble setting up a twitter widget?

I have developed a custom jQuery plugin that displays a sidebar on the left for social media content. The variable below contains the source of the content. I am currently facing an issue while trying to integrate a Twitter feed using the widget, as it keeps showing the error "TWTR is not defined". Any suggestions on how to resolve this?

The plugin I created can be accessed on this page

var content = (
            '<div class="contentArea visible" id="fb">FB Content Area</div>'+
            '<div class="contentArea" id="twit"><script src="http://widgets.twimg.com/j/2/widget.js"></script><script>new TWTR.Widget({version: 2,type: \'profile\',rpp: 4,interval: 6000,width: 250,height: 280,theme: {shell: {background: \'#333333\',color: \'#ffffff\'},tweets: {background: \'#ffffff\',color: \'#444444\',links: \'#e02046\'}},features: {scrollbar: false,loop: false,live: false,hashtags: true,timestamp: true,avatars: false,behavior: \'all\'}}).render().setUser(\'CSuitesIndepend\').start();</script></div>'+
            '<div class="contentArea" id="youtube">Youtube Video</div>'+
            '<div class="contentArea" id="yelp">Yelp reviews</div>'+
            '<div class="contentArea" id="ta">Trip Advisor Advice</div>'+
            '<div class="contentArea" id="li">The Linked In Page</div>'
        );

Furthermore, if I remove the line

<script src="http://widgets.twimg.com/j/2/widget.js"></script>
from the plugin and place it in the head section of my webpage, only the Twitter feed appears.

EDIT: I was thinking why couldn't I simply append the Twitter widget code -

<script>
new TWTR.Widget({
  version: 2,
  type: 'profile',
  rpp: 4,
  interval: 6000,
  width: 250,
  height: 280,
  theme: {
    shell: {
      background: '#333333',
      color: '#ffffff'
    },
    tweets: {
      background: '#ffffff',
      color: '#444444',
      links: '#e02046'
    }
  },
  features: {
    scrollbar: false,
    loop: false,
    live: false,
    hashtags: true,
    timestamp: true,
    avatars: false,
    behavior: 'all'
  }
}).render().setUser('CSuitesIndepend').start();
</script>
- to the dynamically inserted element via the plugin?

However, when attempting this code, nothing gets inserted into #tweetFeed.

$(document).ready(function() {

        // add the sidebar plugin
        $('html').social(function() {
            //console.log('#tweetFeed = '+ $('#tweetFeed').parent().html());
            $('#tweetFeed').insertAfter("<p>TEST</p>");
        }); 

        //console.log('#tweetFeed = '+ $('#tweetFeed').parent().html());
        $('#tweetFeed').insertAfter("<p>TEST</p>");
    });

Answer №1

Did you know there is a nifty hidden feature that lets you specify the id of the element where you want to load the widget? By using $.getScript in conjunction with the standard twitter widget code, I successfully loaded it into my desired location.

Check out the script I utilized below:


    $(document).ready(function(){
    $.getScript('http://widgets.twimg.com/j/2/widget.js', function () {
    new TWTR.Widget({
    version: 2,
    type: 'profile',
    id : 'twitterBox',
    rpp: 4,
    interval: 30000,
    width: 'auto',
    height: 'auto',
    theme: {
    shell: {
        background: 'transparent', //this is important
        color: '#333'
    },
    tweets: {
      background: 'transparent', //this is important
          color: '#666',
      links: '#d14836'
    }
    },
    features: {
    scrollbar: false,
    loop: false,
    live: false,
    behavior: 'all'
    }
    }).render().setUser('username').start();
    });

    });

Answer №2

When adding a reference to the Twitter javascript file within your markup, ensure that you are also referencing an object within the script. It may take a moment for the browser to download the Twitter js file, but it will still parse your inline script right away.

To address this issue, consider removing the reference to the Twitter script from your markup variable, fetch it using $.getScript(), and then add the markup with a callback from $.getScript. This way, your inline script will only run once the Twitter js file has been loaded by the browser. Here is an example of how you can achieve this:

    var content = (
        '<div class="contentArea visible" id="fb">FB Content Area</div>'+
        '<div class="contentArea" id="twit"><script>new TWTR.Widget({version: 2,type: \'profile\',rpp: 4,interval: 6000,width: 250,height: 280,theme: {shell: {background: \'#333333\',color: \'#ffffff\'},tweets: {background: \'#ffffff\',color: \'#444444\',links: \'#e02046\'}},features: {scrollbar: false,loop: false,live: false,hashtags: true,timestamp: true,avatars: false,behavior: \'all\'}}).render().setUser(\'CSuitesIndepend\').start();</script></div>'+
        '<div class="contentArea" id="youtube">Youtube Video</div>'+
        '<div class="contentArea" id="yelp">Yelp reviews</div>'+
        '<div class="contentArea" id="ta">Trip Advisor Advice</div>'+
        '<div class="contentArea" id="li">The Linked In Page</div>'
    );
    $.getScript("http://widgets.twimg.com/j/2/widget.js",function(){ 
        // dynamically add the get social sidebar
    $('body').prepend('<div id="social"><div id="outer"><span><img src="getSocial.png" alt="Get Social" />' +
              '<ul id="icons"><li><img class="tiny" src="fb.png" alt="Facebook" /></li>'+
              '<li><img class="tiny" src="twit.png" alt="Twitter" /></li></ul></span>'+
              '</div><div id="inner"><div id="innest"><div id="message">Get Social With Comfort Suites!</div>'+
              '<div id="close"><a id="closeB" href="#">X</a></div><ul class="idTabs">'+
              imgs +'</ul>'+content +'</div></div></div>'); 

    });

Consider moving the inline script outside the string being appended to the DOM and placing it directly into the callback function. This approach allows for cleaner passing of variables to the script, especially if options need to be sent to the plugin in the future. By doing so, you won't need to escape quotes and tools like jsHint can assess the script more effectively.

Additionally, explore another method for creating markup with jQuery which could make changes easier to track in version control diffs. It's a personal preference but worth considering.

I hope these insights are helpful!

Update:

It seems that when the widget is created (new TWTR.Widget), it automatically calls .init() and inserts the HTML code at that exact point. This behavior causes it to overwrite other content on the page since we're invoking it in a script placed in the head section.

Try encapsulating the "new TWITR.Widget" call within a function and then call that function from an inline script in your markup where the widget should appear. This way, variables remain external to the markup, and the inline script simply references a function defined in the head script.

Here is an example function setup for the Twitter widget:

var makeTwitterWidget = function () {
    new TWTR.Widget({
        version: 2,
        type: 'profile',
        rpp: 4,
        interval: 6000,
        width: 250,
        height: 280,
        theme: {
            shell: {
                background: '#333333',
                color: '#ffffff'
            },
            tweets: {
                background: '#ffffff',
                color: '#444444',
                links: '#e02046'
            }
        },
        features: {
            scrollbar: false,
            loop: false,
            live: false,
            hashtags: true,
            timestamp: true,
            avatars: false,
            behavior: 'all'
        }
    })
    .render()
    .setUser('CSuitesIndepend')
    .start();
};

Then, adjust the content variable accordingly:

var content = (
    '<div class="contentArea visible" id="fb">FB Content Area</div>'+
    '<div class="contentArea" id="twit"><script>makeTwitterWidget();</script></div>'+
    '<div class="contentArea" id="youtube">Youtube Video</div>'+
    '<div class="contentArea" id="yelp">Yelp reviews</div>'+
    '<div class="contentArea" id="ta">Trip Advisor Advice</div>'+
    '<div class="contentArea" id="li">The Linked In Page</div>'
);

Answer №3

Did you happen to explore the option of using

Answer №4

If you're encountering difficulties, Twitter might have the solution you need,

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A layout featuring a grid design that includes spacing and gutters between items, however, there is no spacing between the items

I am looking to create a grid layout where each child element represents an individual grid square. However, I am facing an issue with spacing between the children and the parent container, which is not desired. How can I eliminate this unwanted space? U ...

Three js is a fantastic tool for creating dynamic 3D visuals with a smoothly rotating

Here is the code I am using to set up my camera and position it: const box = new THREE.Box3().setFromObject(model); const size = box.getSize(new THREE.Vector3()).length(); const center = box.getCenter(new THREE.Vector3()); camera.near = size / 100; camera ...

Having trouble exporting data from Excel using react-data-export

I've been attempting to create an excel export feature, but for some unknown reason, it's not functioning properly. I'm utilizing react-data-export and followed a small test example from this GitHub link, yet the export is not working as exp ...

Extracting information from text using machine learning technology

Suppose I am developing a small Chrome extension primarily using JavaScript. Given a list of strings such as: Artist - Song Name Artist, Song Name Song Name - Artist Irrelevant info - Song Name - Artist and so on. I need to extract only the Song Name ...

Scroll dynamically to a div upon clicking and looping through its content

When the user clicks on the first paragraph with the class "targetgo", I want the page to scroll to the element with the class "size1". The same goes for the second paragraph with the class "size2" and so on. As I will have more than 25 similar instances ...

The backdrop-filter in tandem with mask-image is not functioning as anticipated on the Chrome browser

I am facing an issue with the interaction of the mask-image and backdrop-filter attributes on Chrome v116. My goal is to create a gradient-blur effect over text. While this works correctly in Firefox, Chrome only displays a solid white block. This is how ...

A guide on using Ajax to fetch records and showcase them in a table in Laravel

To display a specific record by ID, I need to use the onclick event in a model. The model is appearing without any details being fetched by the URL function. <button id="{{$res->id}}" class="btn btn-info" data-toggle="modal& ...

Creating dynamic <a> tags using JavaScript

My current view includes a div tag with 2 links - one for displaying the page in English and another for Arabic. I want to modify it so that if the page is already in English, only the Arabic <a> tag will show, and vice versa if the page is in Arabic ...

Is there a way to automatically update a webpage?

When two computers, pc1 and pc2, are on the same page and pc1 changes the status of a field, is there a way to update pc2's aspx page without needing to refresh it? ...

Managing Events for a Menu Item That Cannot Be Selected

As I work on developing a form using Material UI React, my focus is on logging exercise sets to the database. To allow users to select the exercise they wish to log, I have incorporated a list of Material UI Menu Item components as options. Additionally, I ...

Using Codeigniter to handle an array of JSON objects in a POST request

When I check my jQuery post request parameters in Firebug, here is what I see: adults 1 applicants[] [object Object] attendees 1 children 0 The JSON object within the array named applicants in this post request contains data that I nee ...

Counting the number of characters without including HTML tags in C#

I am currently exploring methods to calculate the number of characters in a string, shorten the string, and then return it without including HTML tags in the character count. It's important that HTML tags are not counted because if the truncation poin ...

The export of a corrupted "OffscreenCanvas" is prohibited

Currently, I am implementing a process where an ImageBitmap is passed into a web worker in order to render it on a canvas. Subsequently, a URL is generated for loading into THREE.js on the main thread. Within the main thread this.canvas = this.canvasEl. ...

Sending a request to multiple APIs using a GET method

Issue: I am facing a challenge with handling 47 URLs, each varying by their last one or two characters from 1 to 47. For instance: https://example.com/api/data?number=1 <--- the number at the end ranges from 1 to 47 My objective is to retrieve data ...

Error when attempting to assign values in Javascript

One issue I am facing is the lack of values assigned for variables like fname, lname, etc. These variables do not exist on the page until the success function is triggered and it posts to template/orderForm.php. For instance, if I try to console.log(fname) ...

Is it possible to include aria-controls in an anchor tag?

My primary navigation includes some elements that may have a secondary navigation. In order to optimize accessibility on my website, I am seeking the most effective way to show/hide the secondary nav. After brainstorming, here is what I have come up with: ...

The Yii yiiactiveform function remains undefined when clientValidation is disabled

I am currently using Yii 1.1.14 Instead of using Yii's ajax validation or client validation, I am using a form to capture an email. <?php $form = $this->beginWidget('CActiveForm', array( 'id' => 'form-newsletter ...

Change the value of a boolean cell within my database table

I have a task where I need to dynamically update the status of the show_msg parameter based on user actions. When the submit button is pressed, I want to set it as TRUE if the checkbox is checked, and FALSE if not. The main HTML code includes a popup wind ...

Ways to reload an independent page in order to access PHP session variables:

Starting off, I want to mention that my approach may not be the most efficient. As a novice in JavaScript and PHP, I am aware that there are better and simpler ways to achieve what I'm attempting. The issue seems to be related to session variables an ...

Triangle shape with transparent background on top of iframe or div

Currently facing an issue where I need to add an iframe containing maps to my page. However, I also need one (or two) triangles placed over this iframe with a transparent background. I attempted this solution, but unfortunately, it did not work as expect ...