Reputation: 11
<script>
$(document).ready(function() {
$(".tweets").liveTweets({operator: "#google"});
});
</script>
I like to make the #google as a variable, so that I can change the ticker symbol as needed. I tried to echo with php. But, it's breaking the live tweet jquery.
Thanks!
Upvotes: 0
Views: 839
Reputation: 13421
<?php
$operator = "#google";
?>
<script>
$(document).ready(function() {
$(".tweets").liveTweets({operator: <?php echo json_encode($operator)?>});
});
</script>
EDIT: Thank you for your comment @icktoofay.
He is right, we don't need to wrap output in double quotes, it does that for us. I've just updated it.
Upvotes: 1
Reputation: 179046
HTML belongs in .html
files, CSS belongs in .css
files, and JS belongs in .js
files. If you want to pass additional data from the server (PHP in this case) to JavaScript, you should use [data-*]
attributes.
Wherever you're defining your .tweets
element, you should pass the value you want used for operator
as a custom data-*
attribute:
<?php
$operator = '#google';
?>
<div class="tweets" data-operator="<?php echo htmlspecialchars($operator) ?>">
...contents...
</div>
In your separate JS file, you can then use the custom server variable when initializing the widget:
JS:$('.tweets').each(function () {
$(this).liveTweets({
operator: $(this).data('operator')
});
});
Alternatively, you can use the data-*
attribute to contain the entire JSON object to initialize the widget:
<?php
$liveTweets = array(
'operator' => '#google'
);
?>
<div class="tweets" data-live-tweets="<?php echo htmlspecialchars(json_encode($liveTweets)) ?>">
...contents...
</div>
JS:
$('.tweets').each(function () {
$(this).liveTweets($(this).data('liveTweets'));
});
Also, you could select elements based on the condition of having the appropriate data-*
attribute:
$('[data-live-tweets]').each(function () {
$(this).liveTweets($(this).data('liveTweets'));
});
Upvotes: 0