简体   繁体   中英

Cannot change headings to random colour on page load

When the page loads a random colour is generated and applied to the 'TEST COLOUR' text and the headings of the RSS feed.

http://jsfiddle.net/chrisloughnane/nqkH4/

The trouble is the RSS feed heading's colour does not change.

I setup an event, click 'TEST COLOUR' and the heading colour will change so I've figured it is to do with dynamically added elements.

I have looked at .on() but have not managed to get it to work.

Could someone post the code needed to change the headings colour on page load?

tia

jQuery plugin is FeedEk: http://jquery-plugins.net/FeedEk/FeedEk.html

CODE

$(document).ready(function(){

    $('#divRss').FeedEk({
      FeedUrl : 'http://rss.cnn.com/rss/edition.rss'
    });

    var r = Math.floor(Math.random()*256);
    var g = Math.floor(Math.random()*256);
    var b = Math.floor(Math.random()*256);

    $('#example, .itemTitle a').css("color", getHex(r,g,b));

    $('#example').click(function() {

        $('.itemTitle a').css("color", getHex(r,g,b));

    });

    function intToHex(n){
        n = n.toString(16);
        if( n.length < 2) 
            n = "0"+n; 
        return n;
    }

    function getHex(r, g, b){
        return '#'+intToHex(r)+intToHex(g)+intToHex(b); 
    }

});

HTML

<div id="example">TEST COLOUR</div>
<div id="divRss"></div>

CSS

.feedEkList{width:450px; list-style:none outside none;background-color:#FFFFFF; border:1px solid #D3CAD7; padding:4px 6px; color:#3E3E3E;}
.feedEkList li{border-bottom:1px solid #D3CAD7; padding:5px;}
.feedEkList li:last-child{border-bottom:none;}
.itemTitle a{font-weight:bold; color:#4EBAFF; text-decoration:none }
.itemTitle a:hover{ text-decoration:underline }
.itemDate{font-size:11px;color:#AAAAAA;}

#example { font-weight: bold; cursor: pointer;}

-Edit-

In response to comments below, the timeout is unreliable. I've extended the included library to allow for a callback function. Default is alert('done') , but it can be passed in as an argument to do whatever you'd like.

Updated Fiddle : http://jsfiddle.net/nqkH4/8/

Alternatively, as discussed below, you could poll the contents of your target div to see if its content has changes, when it has, you know the call has completed.

I think the issue is there is a slight delay with content hitting the DOM and the script trying to style it. It've gotten it to work with a small timeout .

 setTimeout(function () {
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    var color = getHex(r, g, b);

    $('#example, .itemTitle a').css("color", color);

}, 50);

Updated Fiddle: http://jsfiddle.net/nqkH4/6/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM